Strings are used to handle text in Python. They are one of the most common data types and come with many built-in tools.
What is a string?
A string is text enclosed in single quotes ' ' or double quotes " ".
name = "Alex"
message = 'Hello, Python!'
multiline = """This is a
multi-line string."""
Strings are immutable, which means you cannot change them directly. Operations create new strings instead.
Basic operations
Concatenate (join) strings with +:
greeting = "Hello" + " " + "Alex"
print(greeting) # Hello Alex
Repeat a string with *:
stars = "*" * 10
print(stars) # **********
Get the length with len():
print(len(name)) # 4
Accessing characters
Use indexes to get individual characters. Indexes start at 0.
text = "Python"
print(text[0]) # P
print(text[-1]) # n (last character)
Slice to get a substring:
print(text[1:4]) # yth
print(text[:3]) # Pyt (from start)
print(text[3:]) # hon (to end)
Common string methods
Convert case:
text = "hello python"
print(text.upper()) # HELLO PYTHON
print(text.lower()) # hello python
print(text.title()) # Hello Python
Replace parts:
message = "I like cats"
new_message = message.replace("cats", "dogs")
print(new_message) # I like dogs
Split into a list:
words = "apple,banana,cherry"
word_list = words.split(",")
print(word_list) # ['apple', 'banana', 'cherry']
Check content:
email = "user@example.com"
print(email.startswith("user")) # True
print(email.endswith(".com")) # True
Formatting strings
Use f-strings for clean formatting:
name = "Alex"
age = 25
print(f"{name} is {age} years old.") # Alex is 25 years old.
Common mistake: trying to change a string directly
Strings are immutable, so this causes an error:
text = "hello"
text[0] = "H" # TypeError: 'str' object does not support item assignment
Create a new string instead:
new_text = "H" + text[1:]
print(new_text) # Hello
Quick summary
- Create strings with quotes.
- Use indexing and slicing to access parts.
- Apply methods like
.upper(),.lower(),.replace(), and.split(). - Use f-strings for easy formatting.
- Remember strings are immutable.
Practice common operations on strings. They are essential for handling text in Python programs.
Top comments (0)