Python – Strings
A string is a list of characters and, in Python, they are easy to declare using speech marks.
myquote = “Talk is cheap. Show me the code.”
Get the length of a String in Python
Getting the length of a string in python is the same as with a list
len(myquote)
Getting a sub string in Python
You can access individual letters in Python using the index (as per a list) e.g
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.
You will often want to split a string into parts. Maybe its a line from a file that you want to see as words or a date that you would like to split into day, month and year.
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
There are a number of different text conversions in Python that convert Strings into a new format e.g.
"HELLO".lower() # returns 'hello'
"world".upper() #returns 'WORLD'
"hello world".title() #returns 'Hello World'
Testing a string for letters, numbers in Python
You can also test a string to see if it contains certain elments or is of a certain type:
"w".isalpha() #returns True
"1".isdigit() #returns True
Replacing Characters in a String
There are a number of ways to replace characters (or sub strings) in a string including regular expressions. The simpliest way to start with is replace. The following example will replace any a with a !
word = "once upon a time" word.replace("a","!")
Other string operations to consider
- You can trim strings in Python
- You can join strings normally with a + or use the join method to include a delimiter (seperating character).