Working with Strings
Read, combine, search, clean, and loop through text with strings.
Strings are text
A string is a sequence of characters inside quotes. You can index and slice it just like a list.
Strings are immutable, so methods return new strings instead of changing the original one.
word = 'Python'
print(word[0])
print(word[-1])
print(word[1:4])
print(word + ' 3')
print('ha' * 3)
The first character is at index 0. + joins strings, and * repeats a string.
Clean and split text
message = ' Hello, Python '
clean = message.strip()
words = clean.lower().split(', ')
print(clean.upper())
print(words)
print(' - '.join(words))
print(clean.replace('Python', 'world'))
strip() removes surrounding whitespace. split() makes a list, while join() turns a sequence of strings into one string.
Find and write special characters
path = r'C:\new\notes'
text = 'first line\nsecond line'
print(path)
print(text)
print('banana'.find('na'))
print('Python'.startswith('Py'))
\n is an escape sequence for a new line. A raw string begins with r, so backslashes are kept as ordinary characters. find() returns the first position or -1; startswith() returns True or False.
name = 'Ada'
print(len(name))
for letter in name:
print(letter)
Key points
- Strings are ordered, immutable characters.
- You can index and slice a string.
- Methods such as upper() return new strings.
- split() makes a list and join() combines strings.
- Use len() and a for loop to work through text.
Worked example
A courier app cleans a typed name and builds a tracking slug from an ID.
raw_name = " md. rahim "
clean = raw_name.strip().title()
slug = "BD-4821".lower().replace("-", "")
print(clean, slug)
How it works, step by step
- .strip() removes surrounding spaces.
- .title() capitalises each word.
- Chaining methods applies them left to right in one expression.
References & Further Reading
Related entries from PyLabs's own reference library.
Practice exercise
Not passed yetSet text = ' red,blue '. Remove surrounding spaces, split on the comma, then join the colors with ' | ' and print the result.
Expected output: red | blue
# Write your code below
Check yourself
Working with Strings quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.