Python > Core Python Basics > Fundamental Data Types > Strings (str)
String Manipulation and Formatting
This snippet demonstrates fundamental string operations, including concatenation, slicing, formatting, and immutability in Python.
String Concatenation and Repetition
This code shows how to combine strings using the `+` operator and repeat a string using the `*` operator. Concatenation joins strings together, while repetition creates a new string by repeating the original string a specified number of times. Note the addition of a space in concatenation for readability.
string1 = "Hello"
string2 = "World"
# Concatenation
combined_string = string1 + " " + string2
print(f"Concatenation: {combined_string}")
# Repetition
repeated_string = string1 * 3
print(f"Repetition: {repeated_string}")
String Slicing
String slicing allows you to extract portions of a string. The syntax is `string[start:end:step]`. `start` is the starting index (inclusive), `end` is the ending index (exclusive), and `step` is the increment between indices. Omitting `start` defaults to 0, and omitting `end` defaults to the end of the string. A negative step reverses the string.
my_string = "Python is awesome"
# Slicing from index 0 to 6 (exclusive)
slice1 = my_string[0:6]
print(f"Slice [0:6]: {slice1}")
# Slicing from index 7 to the end
slice2 = my_string[7:]
print(f"Slice [7:]:{slice2}")
# Slicing from beginning to index 6 (exclusive)
slice3 = my_string[:6]
print(f"Slice [:6]:{slice3}")
# Slicing with a step of 2
slice4 = my_string[0:10:2]
print(f"Slice [0:10:2]: {slice4}")
#Reverse string
reverse_string = my_string[::-1]
print(f"Reverse string[::-1]: {reverse_string}")
String Formatting (f-strings)
F-strings (formatted string literals) provide a concise way to embed expressions inside string literals, using curly braces `{}`. They are evaluated at runtime and offer a readable and efficient way to format strings.
name = "Alice"
age = 30
# Using f-strings for formatting
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
# Using expressions within f-strings
result = 10 + 5
formatted_expression = f"The result of 10 + 5 is {result}"
print(formatted_expression)
String Immutability
Strings in Python are immutable, meaning their values cannot be changed after they are created. Attempting to modify a character in a string directly will raise a `TypeError`. To 'modify' a string, you must create a new string based on the original.
# Strings are immutable
my_string = "Hello"
# Attempting to modify a string directly will result in an error
# my_string[0] = "J" # This will raise a TypeError
#To change the string we need to build another one
new_string = 'J' + my_string[1:]
print(f"Changing first char: {new_string}")
Real-Life Use Case Section
Strings are extensively used in data processing, web development, and scripting. For example, parsing log files, extracting information from text documents, or creating dynamic web pages all heavily rely on string manipulation. Consider a scenario where you need to extract usernames from a list of email addresses; string slicing and splitting become essential tools.
# Extracting usernames from email addresses
email_addresses = ["john.doe@example.com", "jane.smith@company.net", "peter.jones@domain.org"]
usernames = [email.split("@")[0] for email in email_addresses]
print(f"Usernames: {usernames}")
Best Practices
Interview Tip
Be prepared to discuss string immutability and its implications. Understand how slicing works and common string methods like `.split()`, `.join()`, `.lower()`, and `.upper()`. Practice writing code to solve string-related problems.
When to use them
Memory footprint
Strings in Python are stored as sequences of Unicode characters. Longer strings naturally consume more memory. Be aware that each string operation creating a new string (due to immutability) allocates memory. Using techniques like string interning (Python automatically interns some small strings) and `.join()` can help optimize memory usage.
Alternatives
Pros
Cons
FAQ
-
Why are strings immutable in Python?
String immutability allows Python to optimize memory usage and simplifies object management. It also prevents unintended side effects when passing strings as arguments to functions. -
How can I efficiently build a large string from a list of smaller strings?
Use the `.join()` method: `"".join(my_list)`. This is more efficient than repeated concatenation using `+`.