What are Strings in Python?
Strings in Python are sequences of characters enclosed in single, double, or triple quotes. They are one of the most commonly used data types and come with a plethora of built-in methods for manipulation.
Creating Strings
Examples:
# Single and double quotes
string1 = 'Hello'
string2 = "World"
# Triple quotes (for multi-line strings)
multi_line_string = """This is a
multi-line string."""
print(string1, string2) # Output: Hello World
print(multi_line_string)
String Operations
Concatenate strings in python
Combine two or more strings using the +
operator.
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message) # Output: Hello, Alice!
Repetition strings in python
Repeat a string using the *
operator.
repeated = "Ha" * 3
print(repeated) # Output: HaHaHa
Membership Testing
Check if a substring exists in a string using in
or not in
.
sentence = "Python is fun"
print("Python" in sentence) # Output: True
print("Java" not in sentence) # Output: True
String Indexing and Slicing in Python
Strings are indexed with each character having a position (starting at 0). Use slicing to extract parts of the string.
Examples:
text = "Python"
# Indexing
print(text[0]) # Output: P
print(text[-1]) # Output: n
# Slicing
print(text[0:3]) # Output: Pyt
print(text[2:]) # Output: thon
print(text[:4]) # Output: Pyth
Common String Methods in Python
Method | Description | Example | Output |
---|---|---|---|
lower() | Converts string to lowercase | "HELLO".lower() | hello |
upper() | Converts string to uppercase | "hello".upper() | HELLO |
strip() | Removes whitespace from ends | " hello ".strip() | hello |
replace() | Replaces a substring | "Python".replace("Py", "My") | Mython |
split() | Splits string into a list | "a,b,c".split(",") | ['a', 'b', 'c'] |
join() | Joins list into a string | ",".join(['a', 'b', 'c']) | a,b,c |
find() | Finds the index of a substring | "hello".find("l") | 2 |
startswith() | Checks if string starts with a substring | "hello".startswith("he") | True |
endswith() | Checks if string ends with a substring | "hello".endswith("lo") | True |
String Formatting
1. Using f-strings (Python 3.6+)
Embed expressions in strings using {}
.
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
2. Using format()
template = "My name is {} and I am {} years old."
print(template.format("Alice", 25))
3. Using %
(Old-style formatting)
name = "Alice"
print("Hello, %s!" % name)
Handling Special Characters
Use escape sequences for special characters.
Escape Sequence | Description | Example | Output |
---|---|---|---|
\n | Newline | "Hello\nWorld" | Hello World |
\t | Tab | "Hello\tWorld" | Hello World |
\\ | Backslash | "Backslash: \\" | Backslash: \ |
\' | Single Quote | 'It\'s a test' | It's a test |
\" | Double Quote | "She said, \"Hi!\"" | She said, "Hi!" |
Iterating Through Strings
Strings are iterable, allowing you to loop through them character by character.
Example:
text = "Python"
for char in text:
print(char)
Output:
P
y
t
h
o
n
Best Practices for Working with Strings
Use f-strings for Formatting:
name = "Alice"
print(f"Welcome, {name}!")
Avoid Excessive Concatenation:
- Use
join()
for efficient concatenation:
words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence)
Test Membership Instead of Searching:
- Instead of using
find()
for checks, usein
:
if "Python" in sentence:
print("Found!")
Handle Empty Strings Gracefully:
- Use conditions
if not text:
print("String is empty")
Avoid Manual Looping for String Operations:
- Use built-in methods for performance and clarity.
Practice Exercise
Task: Write a function to count the number of vowels in a string.
Solution:
def count_vowels(text):
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1
return count
print(count_vowels("Hello, World!")) # Output: 3