Strings
String is a series of characters surrounded by '
or "
quote = 'brevity is '
multi_line_quote = '''the
soul of'''
2
3
If you use a "
or '
between the same quote, escape it with \
hamlet_quote = "\"To be or not to be, that is the question\""
Or just use different quotation marks
hamlet_quote = '"To be or not to be, that is the question"'
Formatting
Concatenation is a weird programistic word to denote glueing of word strings.
full_quote = quote + multi_line_quote + ' wit'
# >>> 'brevity is the soul of wit'
2
We can obtain same result but saved in quote
variable
quote += multi_line_quote + ' wit.'
# >>> 'brevity is the soul of wit'
2
Tricky things
text = 'word'
text *= 3 # >>> 'wordwordword'
2
But when we have many strings to glue it becomes a mess. For those situations we have more powerful tool for formating in Python
chemistry_fact = 'Carbohydrates consist of {0}, {1}, and {oxygen}.'.format('C', 'H', oxygen='O')
# >>> Carbohydrates consists of C, H, and O.
2
Substrings
We can pick substrings this way
quote = 'Brevity is the soul of wit'
text = "wordwordword"
quote[1] # >>> 'r' (Second letter in 'Brevity', start counting from 0 index)
quote[:7] # >>> 'brevity' (first 6 characters)
quote[-3:] # >>> 'wit' (last 3 characters)
quote[:-4] # >>> 'Brevity is the soul of' (everything up to the last 4 characters)
new_quote = "In the beginning was the " + text[:4] # (concatenation)
2
3
4
5
6
7
8
There are even more tricks, read the docs.
sample = 'abcdefghi'
every_third = sample[0:9:3] # 'adg'
2
But we can’t do such things
quote[5] = 'z' # >>> ERROR
Length
len(quote) # >>> 26 (string length)
Check and search
Simple check
quote = 'Brevity is the soul of wit.'
search = 'wit' in quote # >>> True
2
Finding position of one string into another (case-sensitive)
quote.find("wit") # >>> 23
quote.find("Wit") # >>> -1 (no 'Wit' in the quote)
2
Another useful check methods
quote.isalpha() # (True if all characters in 'quote' are letters)
quote.isdigit() # (True if there is any character and all characters are numbers)
2
Modification
string = "what is HIP?!"
string.capitalize() # >>> 'What is hip?!'
string.lower() # >>> 'what is hip?!'
string.upper() # >>> 'WHAT IS HIP?!'
string.replace("HIP", "HOP") # >>> "what is HOP?!"
2
3
4
5
6
Cleaning
string = " Ha-ha, you "
string.strip() # >>> 'Ha-ha, you'
string.lstrip() # >>> "Ha-ha, you "
string.rstrip() # >>> " Ha-ha, you"
2
3
4
Unicode
At some point you may need to get byte values of a letters.
chr(65) # >>> 'A' (character from unicode)
ord('A') # >>> 65 (unicode of character)
2
Making lists
We can obtain list from string this way
quote = 'Brevity is the soul of wit.'
new_list = quote.split(" ")
# >>> ['Brevity', 'is', 'the', 'soul', 'of', 'wit.']
2
3
Read more about lists in corresponding file.