Skip to content
Home / Fundamentals

Python String Modification

Case Modification

In Python, there are several built-in methods that allow you to modify the case of a string. Here are some examples:

To Upper Case

To convert a string to upper case, you can use the upper() method. For example:

string = "hello world"
string = string.upper()
print(string)  # Output: "HELLO WORLD"

To Lower Case

To convert a string to lower case, you can use the lower() method. For example:

string = "HELLO WORLD"
string = string.lower()
print(string)  # Output: "hello world"

To Title Case

To convert a string to title case, where the first letter of each word is capitalized and the rest of the letters are lower case, you can use the title() method. For example:

string = "hello world"
string = string.title()
print(string)  # Output: "Hello World"

Advanced examples

# Normalizing the case of a string before performing a case-insensitive search
string = "heLLO World"
search_string = "hello"
normalized_string = string.lower()
if search_string in normalized_string:
    print("Found!")
else:
    print("Not found.")

# Converting a title to sentence case
string = "The Quick Brown Fox JUMPS OVER The Lazy Dog"
string = string.capitalize()
print(string)  # Output: "The quick brown fox jumps over the lazy dog"

# Capitalizing the initials of a name
name = "john smith"
name = " ".join([word.capitalize() for word in name.split()])
print(name)  # Output: "John Smith"

Trimming

Sometimes you may want to remove leading or trailing whitespace from a string. Here are some methods you can use to do this in Python:

Strip

To remove leading and trailing whitespace from a string, you can use the strip() method. For example:

string = "   hello world   "
string = string.strip()
print(string)  # Output: "hello world"

Lstrip

To remove leading whitespace (i.e., whitespace at the beginning of the string), you can use the lstrip() method. For example:

string = "   hello world   "
string = string.lstrip()
print(string)  # Output: "hello world   "

Rstrip

To remove trailing whitespace (i.e., whitespace at the end of the string), you can use the rstrip() method. For example:

string = "   hello world   "
string = string.rstrip()
print(string)  # Output: "   hello world"

Trimming Advanced Examples

# Removing leading and trailing whitespace from user input
string = input("Enter your name: ").strip()
print(f"Your name is {string}.")

# Removing leading and trailing punctuation from a sentence
string = "!Hello, world!"
string = string.strip("!,")
print(string)  # Output: "Hello, world"

# Removing leading and trailing digits from a string
string = "123Hello, world456"
string = string.lstrip("0123456789").rstrip("0123456789")
print(string)  # Output: "Hello, world"

Whitespace Removal

To remove all whitespace from a string, you can use the replace() method and replace all instances of whitespace with an empty string. For example:

string = "   hello   world   "
string = string.replace(" ", "")
print(string)  # Output: "helloworld"

Advanced Examples

# Removing all whitespace from a string before storing it in a database
string = "   Hello   world   "
string = string.replace(" ", "")
print(string)  # Output: "Helloworld"

# Removing all whitespace from a string before comparing it to another string
string1 = " Hello   world "
string2 = "Helloworld"
if string1.replace(" ", "") == string2:
    print("Strings are equal.")
else:
    print("Strings are not equal.")

Replace

The replace() method allows you to replace a specific substring with another string. Here's an example:

string = "hello world"
string = string.replace("world", "universe")
print(string)  # Output: "hello universe"

You can also specify the number of replacements to make. For example, to only replace the first occurrence of a substring, you can do the following:

string = "hello world, hello world"
string = string.replace("hello", "hi", 1)
print(string)  # Output: "hi world, hello world"

Advanced Examples

# Replacing all occurrences of a substring with another string
string = "Hello, world. This is a test."
string = string.replace(" ", "_")
print(string)  # Output: "Hello,_world. This_is_a_test."

# Replacing all occurrences of a substring with another string, but ignoring case
import re
string = "Hello, world. This is a test."
string = re.sub("[hH]ello", "Hi", string)
print(string)  # Output: "Hi, world. This is a test."