STRING FORMATTING
String formatting in Python allows you to create strings with placeholders that can be replaced by the values of variables or expressions. There are multiple ways to do string formatting in Python. Here, I'll explain the three main methods: using the %
operator, using the .format()
method, and using f-strings (formatted string literals), introduced in Python 3.6.
Using %
operator (Old method, but still valid):
name = "Alice"
age = 30
height = 5.8
# Old-style formatting
message = "Hello, %s. You are %d years old and %.2f feet tall." % (name, age, height)
print(message)
Using .format()
method:
name = "Bob"
age = 25
height = 6.0
# Using .format() method
message = "Hello, {}. You are {} years old and {:.2f} feet tall.".format(name, age, height)
print(message)
Using f-strings (Python 3.6+):
name = "Charlie"
age = 35
height = 5.9
# Using f-strings
message = f"Hello, {name}. You are {age} years old and {height:.2f} feet tall."
print(message)
All three methods achieve the same result, but f-strings provide a more concise and readable way of formatting strings, especially when you need to include multiple variables or expressions within a string. Additionally, f-strings offer better performance compared to the .format()
method and the %
operator. Therefore, if you're using Python 3.6 or later, it's recommended to use f-strings for string formatting.
STRINGS
String operations and manipulation in Python involve various built-in methods and operations to work with strings efficiently. Here's an overview of some common string operations and manipulation techniques:
1. Concatenation:
Concatenation is the process of combining two or more strings together.
str1 = "Hello"
str2 = "World"
result = str1 + ", " + str2
print(result) # Output: Hello, World
2. String Formatting:
String formatting allows you to insert values into a string in a formatted manner.
name = "Alice"
age = 30
message = "My name is {} and I am {} years old.".format(name, age)
print(message) # Output: My name is Alice and I am 30 years old.
3. String Methods:
Python provides many built-in string methods for performing various operations such as manipulation, searching, splitting, and more.
my_string = "Hello, World!"
# Convert to uppercase
print(my_string.upper()) # Output: HELLO, WORLD!
# Replace substring
print(my_string.replace("World", "Python")) # Output: Hello, Python!
# Split string into list
print(my_string.split(",")) # Output: ['Hello', ' World!']
# Check if string starts with a substring
print(my_string.startswith("Hello")) # Output: True
4. String Slicing:
String slicing allows you to extract substrings from a string by specifying start and end indices.
my_string = "Hello, World!"
# Extract substring
print(my_string[7:]) # Output: World!
5. String Joining:
String joining is the process of joining multiple strings together using a delimiter.
words = ["Hello", "World", "Python"]
result = ", ".join(words)
print(result) # Output: Hello, World, Python
6. Stripping Whitespace:
Stripping whitespace removes leading and trailing whitespace characters from a string.
my_string = " Hello, World! "
print(my_string.strip()) # Output: Hello, World!
These are just a few examples of string operations and manipulation techniques in Python. Strings are versatile data types, and Python provides many built-in methods and operations to work with them effectively.
Certainly! Here are several more common string methods in Python:
1. .lower()
:
Converts all characters in a string to lowercase.
my_string = "Hello, World!"
print(my_string.lower()) # Output: hello, world!
2. .capitalize()
:
Converts the first character of a string to uppercase and the rest to lowercase.
my_string = "hello, world!"
print(my_string.capitalize()) # Output: Hello, world!
3. .title()
:
Converts the first character of each word in a string to uppercase.
my_string = "hello, world!"
print(my_string.title()) # Output: Hello, World!
4. .swapcase()
:
Swaps the case of each character in a string (lowercase becomes uppercase and vice versa).
my_string = "Hello, World!"
print(my_string.swapcase()) # Output: hELLO, wORLD!
5. .count(substring)
:
Counts the occurrences of a substring within a string.
my_string = "Hello, Hello, World!"
print(my_string.count("Hello")) # Output: 2
6. .find(substring)
:
Returns the lowest index of the substring in the string. Returns -1 if the substring is not found.
my_string = "Hello, World!"
print(my_string.find("World")) # Output: 7
7. .startswith(prefix)
and .endswith(suffix)
:
Checks if the string starts or ends with a specified prefix or suffix.
my_string = "Hello, World!"
print(my_string.startswith("Hello")) # Output: True
print(my_string.endswith("World")) # Output: True
These are just a few more examples of commonly used string methods in Python. They provide various functionalities for manipulating and working with strings effectively.