String manipulation in Python refers to modifying or working with strings in various ways, such as changing their content, formatting them, or extracting specific information from them. Python provides many tools to handle strings and make the manipulation process easy and efficient.
Common String Manipulation Techniques in Python:
1. Concatenation:
You can join two or more strings together using the + operator.
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Output: Hello World
2. Repeating a String:
You can repeat a string multiple times using the * operator.
str1 = "Python "
result = str1 * 3
print(result) # Output: Python Python Python
3. Slicing Strings:
You can extract a part of a string using slicing. The syntax is string[start:end], where:
start is the starting index (inclusive).
end is the ending index (exclusive).
my_string = "Hello, Python!"
slice_result = my_string[0:5] # Extracts from index 0 to 4 (not including 5)
print(slice_result) # Output: Hello
You can also use negative indices to slice from the end of the string:
my_string = "Hello, Python!"
slice_result = my_string[-7:-1] # Extracts from index -7 to -2
print(slice_result) # Output: Python
4. String Formatting:
Using f-strings (Python 3.6+):
You can use f-strings for string formatting, where you can directly embed expressions inside string literals.
name = "Alice"
age = 25
formatted_str = f"Hello, my name is {name} and I am {age} years old."
print(formatted_str) # Output: Hello, my name is Alice and I am 25 years old.
Using format() method:
name = "Bob"
age = 30
formatted_str = "Hello, my name is {} and I am {} years old.".format(name, age)
print(formatted_str) # Output: Hello, my name is Bob and I am 30 years old.
Using % operator:
name = "Charlie"
age = 40
formatted_str = "Hello, my name is %s and I am %d years old." % (name, age)
print(formatted_str) # Output: Hello, my name is Charlie and I am 40 years old.
5. Changing Case:
Converting to Uppercase:
my_string = "hello"
print(my_string.upper()) # Output: HELLO
Converting to Lowercase:
my_string = "HELLO"
print(my_string.lower()) # Output: hello
Capitalizing the First Letter:
my_string = "hello"
print(my_string.capitalize()) # Output: Hello
Title Case (Capitalizing the First Letter of Each Word):
my_string = "hello world"
print(my_string.title()) # Output: Hello World
6. Stripping Whitespace:
strip() – Removes leading and trailing spaces:
my_string = " Python "
print(my_string.strip()) # Output: Python
lstrip() – Removes leading (left) spaces:
my_string = " Python"
print(my_string.lstrip()) # Output: Python
rstrip() – Removes trailing (right) spaces:
my_string = "Python "
print(my_string.rstrip()) # Output: Python
7. Splitting a String into a List of Substrings:
You can split a string into a list based on a delimiter using the split() method.
my_string = "apple,banana,cherry"
result = my_string.split(",")
print(result) # Output: ['apple', 'banana', 'cherry']
You can also limit the number of splits:
my_string = "apple,banana,cherry"
result = my_string.split(",", 1) # Split only once
print(result) # Output: ['apple', 'banana,cherry']
8. Joining a List of Strings into a Single String:
You can combine the elements of a list into a single string using the join() method.
words = ['apple', 'banana', 'cherry']
result = ", ".join(words)
print(result) # Output: apple, banana, cherry
9. Checking Substring Presence:
You can check if a string contains a substring using the in keyword.
my_string = "Python is great"
print("Python" in my_string) # Output: True
print("java" in my_string) # Output: False
10. Replacing Substrings:
You can replace a part of a string with another substring using the replace() method.
my_string = "I like Python"
result = my_string.replace("Python", "Java")
print(result) # Output: I like Java
11. String Alignment:
ljust(width) – Aligns the string to the left, padding it with spaces up to the specified width.
my_string = "Python"
print(my_string.ljust(10, "*")) # Output: Python****
rjust(width) – Aligns the string to the right, padding it with spaces up to the specified width.
my_string = "Python"
print(my_string.rjust(10, "*")) # Output: ****Python
center(width) – Centers the string, padding it with spaces up to the specified width.
my_string = "Python"
print(my_string.center(10, "*")) # Output: **Python**
Example of String Manipulation:
# Given a sentence, we'll manipulate it
sentence = " Hello, Python World! "
# Strip spaces, convert to uppercase, and replace 'WORLD' with 'Universe'
manipulated_sentence = sentence.strip().upper().replace("WORLD", "Universe")
# Split the sentence into words
words = manipulated_sentence.split()
print("Manipulated Sentence:", manipulated_sentence)
print("Words List:", words)
Key Points:
String concatenation can be done using +, and repetition with *.
You can slice strings using the [start:end] syntax.
String formatting can be done using f-strings, format(), or %.
There are many string functions available for manipulation, such as replace(), split(), join(), strip(), and case-changing methods like lower() and upper().
String alignment methods like ljust(), rjust(), and center() help adjust the string layout.
Let me know if you'd like to dive deeper into any of these techniques or need more examples! 😊
0 Comments