Introduction
A string is a sequence of characters. You can pick out one character, take a slice, loop over every character, and use built-in methods that return new strings.
Most of the data a program touches is text: names, messages, addresses, search terms. Knowing how to pull text apart and tidy it up is one of the most practical skills in programming.
How it works
Indexing and slicing
word = "Dhaka"
print(word[0], word[-1])
print(word[1:4])
print(len(word))Positions start at 0: in "Dhaka", word[0] is 'D' and word[4] is 'a'. Negative positions count from the end, so word[-1] is the last character.
A slice word[1:4] takes positions 1, 2 and 3; it stops before 4, just like range. len(word) is the number of characters, 5.
| Expression | Result |
|---|---|
word[0] | 'D' |
word[-1] | 'a' |
word[1:4] | 'hak' |
word[:2] | 'Dh' |
len(word) | 5 |
String methods
name = " rahim uddin "
clean = name.strip().title()
print(clean)
print(clean.upper())
print(clean.replace("Uddin", "Ahmed"))strip()removes spaces at both ends;title()capitalises each word.upper()andlower()change the case.replace(old, new)swaps one piece of text for another.
Methods never change the original string, because strings cannot be changed. Each method returns a new string, so clean holds the result while name keeps its spaces.
Syntax
word[0] # first character
word[-1] # last character
word[1:4] # positions 1, 2 and 3
word[::-1] # reversed
word.strip().lower()
"a" in word
Example
text = "programming"
vowels = 0
for ch in text:
if ch in "aeiou":
vowels += 1
print(vowels)for ch in text: gives one character per round. ch in "aeiou" checks whether the character is a vowel. Step through and watch vowels reach 3 for the letters o, a and i.
Line by line
text = "programming"is the string to examine.vowels = 0starts the count.for ch in text:gives one character on each pass.ch in "aeiou"tests whether that character is a vowel.- The count goes up only when the test passes.
- After the loop,
printshows the total.
Expected result
3
In the real world
Sign-up forms trim and lower-case email addresses, so that Mitu@Example.com and mitu@example.com count as the same person. Search engines, spell checkers and chat filters all begin by going through text character by character.
Common mistakes
word[5]on a 5-letter word is anIndexError: the last position is 4.word[0] = "d"is aTypeError. Build a new string instead:"d" + word[1:].- Calling a method without keeping its result:
name.upper()alone changes nothing; writename = name.upper().
Best practices
- Clean text as soon as you read it, with
stripand a consistent case. - Keep the result of a method, because the original does not change.
- Use
inrather than writing your own search.
Summary
A string is a sequence of characters that you can index, slice and loop over. Strings cannot change, so methods such as upper, strip and replace return new strings.
Practice
Read a word and print it backwards using the slice word[::-1]. Then print YES if the word reads the same both ways, otherwise NO.
Quick check
Key takeaways
- Positions start at 0, and negative positions count from the end.
- A slice stops before its second number.
- Strings cannot be changed, so methods return new ones.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.