Python Tutorial · Python Basics · Lesson 9 of 42

Python Strings

Create strings, slice them, loop over characters and use common string methods.

Creating strings

Strings use single or double quotes; triple quotes span multiple lines.

Example 1Try it yourself
a = "Hello"
b = 'World'
c = """Line one
Line two"""
print(a, b)
print(c)
print(len(a))

Output

Hello World
Line one
Line two
5

Indexing and slicing

Each character has an index starting at 0. Negative indexes count from the end. Slices use [start:end] (end not included).

Example 2Try it yourself
s = "Python"
print(s[0])
print(s[-1])
print(s[0:3])
print(s[2:])
print(s[::-1])  # reversed

Output

P
n
Pyt
thon
nohtyP

Common methods

Strings are immutable — methods return new strings.

Example 3Try it yourself
s = "  Hello, World!  "
print(s.strip())
print(s.lower())
print(s.upper())
print(s.replace("World", "Python"))
print("a,b,c".split(","))
print("-".join(["2026", "10", "12"]))

Output

Hello, World!
  hello, world!  
  HELLO, WORLD!  
  Hello, Python!  
['a', 'b', 'c']
2026-10-12

Checking contents

Example 4Try it yourself
email = "[email protected]"
print("@" in email)
print(email.startswith("ada"))
print(email.endswith(".org"))
print(email.count("a"))
print(email.find("@"))

Output

True
True
False
3
3

Test yourself

What does "Python"[1:4] return?

  1. Pyt
  2. yth
  3. ytho
  4. thon
Show answer

Answer: yth