Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

    Create a variable first_char with the first character of name.

  2. 2

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

  3. 3

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

Back

11/12

  1. 1. Introduction to Lists
  2. 2. Creating Lists
  3. 3. Accessing List Elements
  4. 4. Changing List Elements
  5. 5. Length and the Last Element
  6. 6. Adding Elements: append()
  7. 7. Removing Elements: pop()
  8. 8. Removing by Value: remove()
  9. 9. Searching a List: in
  10. 10. Nested Lists
  11. 11. Characters of a Text
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.