954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

finding what a string starts with

I'm looking for a way to get the first letter of of a string. I already know about the .startswith() but that is for "if" statements I want something like

print text.startswith() # to give me the left most symbol
Thropian
Junior Poster in Training
96 posts since Oct 2010
Reputation Points: 13
Solved Threads: 2
 

Strings are indexable. text[0] is the first symbol.

Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 
>>> d="hello"
>>> d[0]
'h'
>>>


from idle.

richieking
Master Poster
764 posts since Jun 2009
Reputation Points: 61
Solved Threads: 152
 

You can also do string slicing:

s = 'hello'
print(s[:1])  # h

# more
print(s[:2])  # he
print(s[:4])  # hell
bumsfeld
Nearly a Posting Virtuoso
1,445 posts since Jul 2005
Reputation Points: 404
Solved Threads: 184
 

i agree with the splicing which i've found helpful.

codeman11
Newbie Poster
1 post since Jan 2011
Reputation Points: 10
Solved Threads: 1
 

While we're obfuscating

import re
string = "hello world"
first = re.match("(.)", string).group(1)
print(first)
Enders_Game
Newbie Poster
23 posts since Mar 2010
Reputation Points: 23
Solved Threads: 6
 
i agree with the splicing which i've found helpful.


"splicing" is that a secret python slicing method,just kidding :icon_wink:
"splicing" in action.

>>> s = 'hello'
>>> s[::-1][-1]
'h'
>>>
snippsat
Practically a Posting Shark
808 posts since Aug 2008
Reputation Points: 353
Solved Threads: 294
 

cool thanks guys

Thropian
Junior Poster in Training
96 posts since Oct 2010
Reputation Points: 13
Solved Threads: 2
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: