Characters of a Text

Text is not a list, but in some ways it works like one. Each character in a text has an index, counted from 0, and you can read it with square brackets. Negative indexes work too:

language = "Python"
print(language[0])
print(language[1])
print(language[-1])

This prints:

P
y
n

The function len() works for text as well: it gives you the number of characters. Spaces and punctuation marks are characters too, so "Hi, Tom!" has 8 characters:

print(len(language))
print(len("Hi, Tom!"))

This prints:

6
8

Just like with a list, reading past the end of the text ends with an error, this time IndexError: string index out of range.

There is one big difference, though: you can't change a character in a text. Once a text has been created, it stays as it is:

language = "Python"
language[0] = "J"

The program ends with this error:

Traceback (most recent call last):
  File "<exec>", line 2, in <module>
TypeError: 'str' object does not support item assignment

str is Python's name for text (you know it from the function str()), and item assignment means assigning to an element by its index. The message says that text doesn't allow it. If you need a different text, create a new one, for example with + or an f-string, and store it in a variable.

Instructions

Create a variable first_char with the first character of name.

Create a variable last_char with the last character of name. Use a negative index.

Print both characters and the length of the name: print(first_char, last_char, len(name)). The output should be S t 8.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

11/12