Python Strings
Understanding Strings in Python
Strings are one of the most commonly used data types in Python. They represent sequences of characters and are used for storing and manipulating text-based data.
Creating Strings
You can create a string by enclosing characters in single, double, or triple quotes.
text1 = 'Hello'
text2 = "World"
text3 = '''This is a
multiline string'''
'Hello'
and"World"
are equivalent.- Triple quotes (
'''
or"""
) are used for multiline strings.
Accessing Characters in a String
Strings are indexed collections. Each character has a position starting from 0.
word = "Python"
print(word[0]) # First character
print(word[5]) # Last character
Output:
P
n
You can also use negative indexing:
print(word[-1]) # Last character
print(word[-2]) # Second to last character
Output:
n
o
String Slicing
Slicing lets you extract a portion of the string using the syntax [start:stop:step]
.
text = "Hello, World"
print(text[0:5]) # From index 0 to 4
print(text[:5]) # Same as above
print(text[7:]) # From index 7 to the end
print(text[::2]) # Every second character
Output:
Hello
Hello
World
Hlo ol
String Concatenation and Repetition
You can combine strings using +
and repeat them using *
.
greeting = "Hello"
name = "Alice"
message = greeting + " " + name
print(message)
echo = "Hey! " * 3
print(echo)
Output:
Hello Alice
Hey! Hey! Hey!
String Length and Membership
Use len()
to get the length of a string. You can also check if a character or substring exists using the in
keyword.
text = "banana"
print(len(text))
print("a" in text)
print("z" in text)
Output:
6
True
False
String Methods
Python provides many string methods for processing text:
text = " hello world "
print(text.upper()) # Converts to uppercase
print(text.lower()) # Converts to lowercase
print(text.strip()) # Removes leading/trailing spaces
print(text.replace("world", "Python")) # Replaces text
print(text.split()) # Splits string into list
Output:
HELLO WORLD
hello world
hello world
hello Python
['hello', 'world']
Formatting Strings
You can insert variables into strings using f-strings, which are clean and efficient:
name = "Bob"
age = 30
print(f"My name is {name} and I'm {age} years old.")
Output:
My name is Bob and I'm 30 years old.
You can also use .format()
or old-style %
formatting, but f-strings are generally preferred for readability.
Iterating Over Strings
Strings are iterable, which means you can loop through each character:
word = "code"
for letter in word:
print(letter)
Output:
c
o
d
e
Immutability of Strings
Strings in Python are immutable. You cannot change a character by index:
text = "Hello"
# text[0] = "Y" # This will raise an error
To "modify" a string, you must create a new one:
text = "Hello"
new_text = "Y" + text[1:]
print(new_text)
Output:
Yello
Common Use Cases
- Reading input: strings are the default type for user input.
- Parsing files: working with text data from files.
- Web scraping: extracting and cleaning string data.
- Command-line utilities: manipulating arguments and outputs.
Summary
- Strings are ordered, immutable sequences of characters.
- Use indexing and slicing to access and manipulate parts of a string.
- String methods simplify text transformations.
- Use f-strings for clean and readable formatting.
- Strings are not mutable - changes require creating new strings.
Understanding strings is fundamental in Python programming. Mastering their operations will improve your ability to handle real-world data efficiently.
Continue Learning
Python Variables
Popular
### Understanding Variables and Literals in Python Variables and literals are the foundation of any
Personalized Recommendations
Log in to get more relevant recommendations based on your reading history.