Sign in

Intro to Computer Science / Unit 4: Programming Basics in Python

4.5 Strings

3 practice questionsNot yet reviewed

Notes

A string is a sequence of characters. Each character has an index starting at 0.

word = "python"
print(word[0])     # p
print(word[-1])    # n
print(word[1:4])   # yth
print(len(word))   # 6
  • Negative indexes count from the end. A slice s[a:b] starts at index a and stops before b.
  • + joins strings, and * repeats them: "ha" * 3 is "hahaha".
  • Useful methods: .upper(), .lower(), .replace("a", "b"), .strip().
  • Strings are immutable: methods return a new string instead of changing the original.

Practice

With s = "computer", what does print(s[2]) show?
What does print(len("hi there")) display?
What does print("Code".upper() + "!" * 2) display?

Ready for more? Take the Unit 4 test.