Indexing
city = "Kolkata" print(city[0]) print(city[3]) print(city[-1]) print(len(city))
Write Python. Understand every error.
Python basics · topic 7 of 25
A string is a sequence of characters. Each character has a position, called an index, starting from 0. Negative indexes count from the end, so -1 is the last character.
word = "python" print(word[0], word[-1]) # p n
Slicing takes a part of a string: word[1:4] gives the characters at positions 1, 2 and 3. Leaving out a number means "from the start" or "to the end", and word[::-1] reverses the string.
Strings have many built-in methods. They return a new string and never change the original, because strings cannot be changed in place.
len(s) counts the characterss.upper(), s.lower(), s.title() change letter cases.replace("a", "b") swaps texts.count("a") counts occurrences"a" in s checks whether "a" appearslen(s) counts the characters. Positions start at 0, so s[0] is the first character and s[-1] is the last.s[1:4] takes positions 1, 2 and 3. The end position is not included.upper(), replace() and count() return a new string. The original does not change."a" in s checks whether some text appears inside another string.s[10] in a five-letter word. Read the IndexError guide.s[0] = "J". Strings cannot be changed in place. Read the TypeError guide.s.uppercase(). The name is upper(). Read the AttributeError guide.
city = "Kolkata" print(city[0]) print(city[3]) print(city[-1]) print(len(city))
word = "programming" print(word[0:3]) print(word[3:]) print(word[:-4]) print(word[::-1])
s = "python is fun" print(s.upper()) print(s.title()) print(s.replace("fun", "powerful")) print(s.count("n")) print("fun" in s)
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
s = "Python" print(s[1], s[-1])
Indexes start at 0, so s[1] is the second letter. s[-1] is the last letter.
s = "Kolkata" print(s[0:3])
A slice [0:3] takes indexes 0, 1 and 2. The end index is not included.
print("banana".count("a"))
"banana" has three a characters.
print("hello world".title())
.title() capitalises the first letter of each word.
s = "abc" print(s * 2, len(s))
s * 2 repeats the string and len(s) counts its characters.