Last updated

Python Strings

Definition: A string is a piece of text, written inside single or double quotes. Both quote styles work the same way.

a = "Hello"
b = 'World'
print(a, b)

Example 1 — joining (concatenation)

first = "Talented"
last = "Hub"
full = first + " " + last
print(full)

Example 2 — length and changing case

text = "Python"
print(len(text))        # 6 characters
print(text.upper())     # PYTHON
print(text.lower())     # python
print(text.replace("Py", "My"))

Example 3 — picking characters (indexing)

Each character has a position, starting at 0. Negative numbers count from the end:

word = "Python"
print(word[0])    # P  (first)
print(word[2])    # t
print(word[-1])   # n  (last)

Example 4 — slicing (a part of the string)

word = "Python"
print(word[0:3])   # Pyt  (positions 0,1,2)
print(word[2:])    # thon

Example 5 — f-strings (the clean way to mix in values)

name = "Sam"
age = 20
print(f"{name} is {age} years old")

💡 Tip: f-strings (an f before the quote) are the modern, readable way to build messages from variables.

Try it Yourself
Output

          
Ad · responsive