String manipulation is a fundamental aspect of programming, and Python provides a rich set of built-in functions and methods to effectively work with strings. Whether you’re a beginner or an experienced Python developer, having a solid understanding of string manipulation techniques can greatly enhance your ability to process, transform, and analyze textual data.
In this article, we will explore 20 essential code examples that demonstrate various string manipulation operations in Python.
Counting Characters: Count the number of occurrences of a specific character in a string.
text = "Hello, world!"
count = text.count('o')
print(count) # Output: 2
Reversing a String: Reverse the order of characters in a string.
text = "Python"
reversed_text = text[::-1]
print(reversed_text) # Output: nohtyP
Splitting a String: Split a string into a list of substrings based on a delimiter.
text = "Hello,world,how,are,you"
words = text.split(',')
print(words) # Output: ['Hello', 'world', 'how', 'are', 'you']
Joining Strings: Join a list of strings into a single string using a delimiter.
words = ['Hello', 'world', 'how', 'are', 'you']
text = '-'.join(words)
print(text) # Output: Hello-world-how-are-you
Changing Case: Convert a string to uppercase or lowercase.
text = "Hello, world!"
uppercase = text.upper()
lowercase = text.lower()
print(uppercase) # Output: HELLO, WORLD!
print(lowercase) # Output: hello, world!
Removing Whitespace: Remove leading and trailing whitespace from a string.
text = " Hello, world! "
trimmed_text = text.strip()
print(trimmed_text) # Output: Hello, world!
Checking Prefix and Suffix: Check if a string starts or ends with a specific substring.
text = "Hello, world!"
starts_with_hello = text.startswith("Hello")
ends_with_world = text.endswith("world!")
print(starts_with_hello) # Output: True
print(ends_with_world) # Output: True
Finding Substring: Find the index of the first occurrence of a substring in a string.
text = "Hello, world!"
index = text.find("world")
print(index) # Output: 7
Replacing Substring: Replace occurrences of a substring with another substring.
text = "Hello, world!"
new_text = text.replace("world", "Python")
print(new_text) # Output: Hello, Python!
Checking Alphanumeric: Check if a string contains only alphanumeric characters.
text = "Hello123"
is_alphanumeric = text.isalnum()
print(is_alphanumeric) # Output: True
Checking Digit: Check if a string contains only digits.
text = "123"
is_digit = text.isdigit()
print(is_digit) # Output: True
Checking Alpha: Check if a string contains only alphabetic characters.
text = "Hello"
is_alpha = text.isalpha()
print(is_alpha) # Output: True
Checking Title Case: Check if a string is in title case (first letter of each word capitalized).
text = "Hello, World!"
is_title_case = text.istitle()
print(is_title_case) # Output: True
Checking Empty String: Check if a string is empty or consists only of whitespace.
text = " "
is_empty = not text.strip()
print(is_empty) # Output: True
Concatenating Strings: Concatenate two or more strings.
str1 = "Hello"
str2 = "world"
concatenated = str1 + ", " + str2 + "!"
print(concatenated) # Output: Hello, world!
Checking if String Contains a Substring: Check if a string contains a specific substring.
text = "Hello, world!"
contains_hello = "hello" in text.lower()
print(contains_hello) # Output: True
Extracting Substring: Extract a specific substring from a string using slicing.
text = "Hello, world!"
substring = text[7:12]
print(substring) # Output: world
Padding Strings: Pad a string with a specified character or whitespace to a desired length.
text = "Python"
padded_text = text.ljust(10, '*')
print(padded_text) # Output: Python****
Repeating Strings: Repeat a string multiple times.
text = "Hello!"
repeated_text = text * 3
print(repeated_text) # Output: Hello!Hello!Hello!
Checking String Start/End: Check if a string starts or ends with a specific substring using startswith()
and endswith()
methods.
text = "Hello, world!"
starts_with_hello = text.startswith("Hello")
ends_with_exclamation = text.endswith("!")
print(starts_with_hello) # Output: True
print(ends_with_exclamation) # Output: False