Python Strings : Modify Strings

In Python, strings are immutable, which means you cannot modify them directly. However, you can create new strings based on modifications to the original. Below are some ways to “modify” strings:

1. Concatenation

You can join two or more strings together using the + operator.

s1 = "Hello"
s2 = "World"
new_string = s1 + " " + s2
print(new_string)  # Output: "Hello World"

2. Replace Substrings

You can use the replace() method to replace occurrences of a substring with another substring.

s = "Hello World"
new_string = s.replace("World", "Python")
print(new_string)  # Output: "Hello Python"

3. Uppercase, Lowercase, Title Case

You can change the case of strings with methods like upper(), lower(), title(), and capitalize().

s = "hello world"
print(s.upper())     # Output: "HELLO WORLD"
print(s.lower())     # Output: "hello world"
print(s.title())     # Output: "Hello World"
print(s.capitalize())# Output: "Hello world"

4. Slicing

You can access parts of a string using slicing.

s = "Hello World"
new_string = s[0:5]  # Extracts "Hello"
print(new_string)

5. Remove Whitespace

You can use strip(), lstrip(), and rstrip() to remove whitespace from strings.

s = "  Hello World  "
new_string = s.strip()
print(new_string)  # Output: "Hello World"

6. Join

Use the join() method to join elements of a list or tuple into a string.

list_of_strings = ["Hello", "World"]
new_string = " ".join(list_of_strings)
print(new_string)  # Output: "Hello World"

7. Split a String

Use split() to divide a string into a list based on a delimiter.

s = "Hello World"
split_string = s.split()
print(split_string)  # Output: ['Hello', 'World']

8. String Formatting

You can modify and format strings using f-strings, format(), or the % operator.

name = "John"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
Leave a Reply 0

Your email address will not be published. Required fields are marked *