Working With Strings
Strings come with many built-in methods that return a new, changed string. Remember that strings are immutable, so these methods never change the original; they hand back a new value you can store.
Changing Case and Trimming
The upper() and lower() methods change letter case. The strip() method removes spaces from both ends, which is helpful after reading user input.
print('hello'.upper()) # HELLO
print('HELLO'.lower()) # hello
print(' hi '.strip()) # hi
Splitting and Joining
The split() method breaks a string into a list at a chosen separator. The join() method does the reverse, gluing a list of strings together with a separator.
parts = 'a,b,c'.split(',')
print(parts) # ['a', 'b', 'c']
print('-'.join(['a', 'b'])) # a-b
Searching and Replacing
The replace() method swaps one piece of text for another. The find() method returns the index where text first appears, or a negative one when it is not found. Methods like startswith() return True or False.
print('hello'.replace('l', 'L')) # heLLo
print('hello'.find('l')) # 2
print('ab'.startswith('a')) # True
f-strings for Formatting
The cleanest way to build strings from values is an f-string. Put the letter f before the opening quote, then place variables or expressions inside curly braces.
name = 'Sara'
age = 20
print(f'{name} is {age}') # Sara is 20
print(f'{2 + 3}') # 5
You can also format numbers inside an f-string, such as fixing the number of decimal places, which is far tidier than joining many pieces with plus signs.
Chaining Methods Together
Because each method returns a new string, you can chain several together in one line. Python works from left to right, passing each result into the next call. This is a common way to tidy messy input in a single readable step.
raw = ' Hello World '
clean = raw.strip().lower().replace(' ', '-')
print(clean) # hello-world
These methods are the everyday tools of text processing. Whenever you need to tidy user input, split a line of data, or build a friendly message, one of the string methods above will usually do the job clearly and with very little code.
Remember
- String methods return a new string; the original is unchanged.
- upper(), lower(), and strip() clean up text and case.
- split() makes a list; join() combines a list into a string.
- find() returns the first index or a negative number if not found.
- f-strings place variables inside curly braces for clean output.