Python – Strings



Get the length of a String in Python



Getting a sub string in Python


myquote[3] #returns k

but also you can return a sub string e.g.

myquote[8:13] #returns 'cheap'
myquote[-1] #returns '.' or the last letter.
myquote[:6] #returns 'Talk i'
myquote[5:] #returns 'is cheap. Show me the code.'

This SO answer has a good explanation of slices.

Spliting Strings.


myquote= "Task is cheap.  Show me the code"
myquote.split(" ") #returns ['Talk', 'is', 'cheap.', 'Show', 'me', 'the', 'code.']
adate = "23/12/1973"
adate.split("/") #returns ['23', '12', '1973']

Converting text in a Python String


"HELLO".lower() # returns 'hello'
"world".upper() #returns 'WORLD'
"hello world".title() #returns 'Hello World'

Testing a string for letters, numbers in Python


"w".isalpha() #returns True
"1".isdigit() #returns True

Replacing Characters in a String


word = "once upon a time"

Other string operations to consider

  • You can trim strings in Python

Leave a Reply

