A string is a piece of text. You write it inside single or double quotes; both work the same way.
greeting = 'Hello'
place = "Kuala Lumpur"
Joining and repeating
The plus sign joins strings (this is called concatenation), and the star repeats one:
full = 'Hello' + ' ' + 'world' # 'Hello world'
line = 'ab' * 3 # 'ababab'
Length and indexing
Use len() for the number of characters. Index positions start at 0, and negative indexes count from the end:
word = 'Python'
print(len(word)) # 6
print(word[0]) # P
print(word[-1]) # n
Slicing
A slice takes a range of characters. The start is included and the end is excluded:
word = 'Python'
print(word[0:3]) # Pyt
print(word[2:]) # thon
Useful methods
- upper() and lower() change the case.
- strip() removes spaces from the ends.
- replace(a, b) swaps text a for b.
name = ' ali '
print(name.strip().upper()) # ALI
f-strings
An f-string lets you drop variables straight into text. Put an f before the quote and wrap the variable in braces:
name = 'Sara'
age = 12
print(f'{name} is {age}') # Sara is 12
More handy methods
- count(x) counts how many times x appears.
- find(x) gives the index where x first appears, or -1 if not found.
- startswith(x) and endswith(x) return True or False.
text = 'banana'
print(text.count('a')) # 3
print(text.startswith('ba')) # True
Splitting and joining
split() breaks a string into a list of pieces, and join() glues a list back into one string:
parts = 'red,green,blue'.split(',')
print(parts) # ['red', 'green', 'blue']
Checking what is inside
The in keyword tests whether a smaller string appears inside a bigger one:
print('an' in 'banana') # True
print('z' in 'banana') # False
This is a quick way to search text without writing a loop.
Escaping quotes
If your text contains a quote, use the other kind of quote around it so Python does not get confused:
sentence = "It's sunny today"
print(sentence) # It's sunny today
Here double quotes wrap the string so the single quote inside is just an ordinary character.
Remember
- The first character is at index 0, not 1.
- In a slice the end position is not included.
- Strings cannot be changed in place; methods return a new string.