String Indexing and Slicing

45 min read Working with Strings

This is a free course. Log in to run the code exercises and track your progress.

String Indexing and Slicing

A string is a sequence of characters. Each character has an index: counting from the left starts at 0, counting from the right starts at -1.

word = "PYTHON"
# index:  0  1  2  3  4  5
# index: -6 -5 -4 -3 -2 -1
print(word[0], word[-1])   # P N
print(len(word))           # 6

A slice s[start:stop] takes the characters from start up to, but not including, stop. A third value is the step, and a step of -1 walks backwards, so s[::-1] is the string reversed.

print(word[0:3])   # PYT
print(word[2:])    # THON
print(word[::-1])  # NOHTYP

Strings are immutable: word[0] = "J" raises a TypeError. To change a string, build a new one, for example "J" + word[1:].

Python exercise

Read a word and print it reversed on the first line. On the second line print Palindrome if the word reads the same backwards (ignoring upper and lower case), else Not Palindrome.

word = input()
reversed_word = word  # use a slice with step -1
print(reversed_word)
if word == reversed_word:
    print("Palindrome")
else:
    print("Not Palindrome")

Log in to edit and run this code.