Strings are one of the most commonly used data types in Python. Whether you're reading user input, processing text data, or working with files, you'll be using strings a lot.
In this article, you'll learn everything about Python strings, including:
-
What they are
-
How to create and manipulate them
-
String methods
-
Formatting techniques
-
Tips and common mistakes
What is a String?
A string is a sequence of characters enclosed in quotes.
✅ You can use:
-
Single quotes
' '
-
Double quotes
" "
-
Triple quotes
''' '''
or""" """
(for multi-line strings)
Example:
name = "Alice"
message = 'Hello, World!'
paragraph = """This is a
multi-line string."""
Accessing Characters in a String
Strings are indexed, starting from 0
. You can access individual characters using brackets:
name = "Python"
print(name[0]) # Output: P
print(name[-1]) # Output: n (last character)
String Slicing
You can extract parts of a string using slicing:
s = "Hello, World!"
print(s[0:5]) # Output: Hello
print(s[:5]) # Output: Hello (start is optional)
print(s[7:]) # Output: World!
print(s[-6:-1]) # Output: World
Syntax: string[start:stop]
(stop index is excluded)
➕ String Concatenation and Repetition
Concatenation:
first = "Hello"
last = "World"
print(first + " " + last) # Output: Hello World
Repetition:
print("Ha" * 3) # Output: HaHaHa
Looping Through Strings
word = "Python"
for char in word:
print(char)
String Methods (Built-in Functions)
Python provides many helpful string methods:
Method | Description | Example |
---|---|---|
.lower() |
Converts to lowercase | "HELLO".lower() → "hello" |
.upper() |
Converts to uppercase | "hi".upper() → "HI" |
.strip() |
Removes whitespace | " hi ".strip() → "hi" |
.replace(a, b) |
Replace substring | "Hello".replace("l", "x") → "Hexxo" |
.split() |
Splits string into list | "a,b,c".split(",") → ["a", "b", "c"] |
.join() |
Joins list into string | "-".join(["a", "b", "c"]) → "a-b-c" |
.find() |
Returns first index of substring | "hello".find("e") → 1 |
.startswith() |
Checks prefix | "hello".startswith("he") → True |
.endswith() |
Checks suffix | "hello".endswith("o") → True |
String Formatting
1. f-strings (Recommended, Python 3.6+)
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
2. str.format()
method
print("My name is {} and I am {} years old.".format(name, age))
3. % formatting (old style)
print("My name is %s and I am %d years old." % (name, age))
Example: Word Reversal Tool
text = input("Enter a word: ")
reversed_text = text[::-1]
print(f"The reversed word is: {reversed_text}")
String Length
Use len()
to get the number of characters:
s = "Python"
print(len(s)) # Output: 6
Escape Characters
Use backslash \
to insert special characters:
Escape | Meaning |
---|---|
\n |
Newline |
\t |
Tab |
\\ |
Backslash |
\" |
Double quote |
\' |
Single quote |
print("Hello\nWorld")
print("She said, \"Hi!\"")
Raw Strings
Use r"..."
to ignore escape characters (common in file paths):
path = r"C:\Users\Alice"
print(path)
Tips for Working with Strings
-
Use f-strings for clean and efficient formatting.
-
Remember strings are immutable – you can’t change characters directly.
-
Use
.strip()
to clean up input from users or files. -
Break long strings using
\
or parentheses:
long_string = (
"This is a very long string "
"that spans multiple lines."
)
⚠️ Common Pitfalls
Mistake | Explanation |
---|---|
Using + too much |
Prefer join() for efficiency when combining many strings |
Forgetting strings are immutable | You can't do s[0] = 'X' |
Misusing escape characters | Use raw strings or escape properly |
Mixing strings and numbers | Use str() or int() to convert types |
What's Next?
Once you're comfortable with strings, dive deeper into:
-
Regular expressions (with the
re
module) -
String encoding and decoding
-
Text processing and file I/O
Summary
Concept | Example |
---|---|
Create a string | s = "Hello" |
Access character | s[1] → 'e' |
Slice string | s[0:4] → 'Hell' |
Concatenate | "Hi" + "!" → 'Hi!' |
Format | f"{name} is {age}" |
Methods | .lower() , .replace() , .split() |