Page Contents
Hi All. In this post we will understand string manipulation using some built-in functions. String is a sequence of character. Python provides built-in methods that operates on Strings. String manipulation involves performing various operations on strings, such as concatenation, slicing, formatting, and more. Here are some common string manipulation techniques in Python.
String manipulation examples
Concatenation
# Example : Concatenating two string using "+" str1 = "Hello" str2 = "Proedu.co" result = str1 + " " + str2 print(result)
String Formatting
Python provides format() method which formats the specified value and insert it in the placeholder. Placeholders are defined by curly brackets.
string.format(value1, value2…)
# Example 1 message = "My name is {name} and I am {age} years old." print(message.format(name="Shivaay", age=6)) # Output : My name is Shivaay and I am 6 years old. # Example 2 name = "Shivaay" age = 6 message = f"My name is {name} and I am {age} years old." print(message) # Output : My name is Shivaay and I am 6 years old. # Example 3 : Show price with two-decimal format. price = 100 print(f"The price is {price:.2f}") # Output : The price is 100.00 # Example 4 : Using the placeholders in different ways. print("My name is {name}, I'm {age} years old".format(name = "Shivaay", age = 6)) print("My name is {0}, I'm {1} years old".format("Shivaay",6)) print("My name is {}, I'm {} years old".format("Shivaay",6)) #
Cut or Extract a portion of a string using slicing
In Python, you can cut or extract a portion of a string using slicing. Slicing allows you to create a new string that consists of a specified range of characters from the original string. Here are some examples:
# Example 1 word = "Hello, Proedu!" # Extract characters from index 7 (Inclusive) to 13 (exclusive) substring = word[7:13] print("Original String:", word) print("Substring:", substring) # Output: # Original String: Hello, Proedu! # Substring: Proedu #
Slicing with Stride.
# Example 2: Slicing with Stride. word = "Hello, Proedu!" # Extract characters with a stride of 2 substring = word[::2] print("Original String:", word) print("Substring:", substring) # Output # Original String: Hello, Proedu! # Substring: Hlo reu #
Negative Index Slicing
Negative indices count from the end of the string.
# Negative Index Slicing. Negative indices count from the end of the string. word = "Hello, Proedu!" substring = word[-7:] print("Original String:", word) print("Substring:", substring) # Output # Original String: Hello, Proedu! # Substring: Proedu!
String Built-in functions
len() – Length of a String:
# len() - Length of a String: word = "Hello, Proedu!" length = len(word) print("Length of the string:", length) # Output: Length of the string: 14
lower() – Convert to Lowercase:
# lower() - Convert to Lowercase: word = "Hello, Proedu!" lower_case = word.lower() print("Lowercase:", lower_case) # Output: Lowercase: hello, proedu!
upper() – Convert to Uppercase:
# upper() - Convert to Uppercase: word = "Hello, Proedu!" upper_case = word.upper() print("Uppercase:", upper_case) # Output: Uppercase: HELLO, PROEDU!
capitalize() – Capitalize First Letter
# capitalize() - Capitalize First Letter: word = "hello, Proedu!" capitalized = word.capitalize() print("Capitalized:", capitalized) # Capitalized: Hello, proedu!
title() – Capitalize First Letter of Each Word
# title() - Capitalize First Letter of Each Word: word = "hello, Proedu!" title_case = word.title() print("Title Case:", title_case) #Output: Title Case: Hello, Proedu!
count() – Count Occurrences of a Substring
# count() - Count Occurrences of a Substring: word = "Hello, Hello, Proedu!" count_occurrences = word.count("Hello") print("Occurrences of 'Hello':", count_occurrences) # Occurrences of 'Hello': 2
find() – Find Substring (Returns Index)
# find() - Find Substring (Returns Index): word = "Hello, Proedu!" index = word.find("Proedu") print("Index of 'Proedu':", index) #Output: Index of 'Proedu': 7
replace() – Replace Substring
# replace() - Replace Substring: word = "Hello, Proedu!" new_string = word.replace("Proedu", "Universe") print("Replaced String:", new_string) #Output: Replaced String: Hello, Universe!
strip() – Remove Leading and Trailing Whitespace
# strip() - Remove Leading and Trailing Whitespace: word = " Hello, Proedu! " stripped_string = word.strip() print("Stripped String:", stripped_string) # Output: Stripped String: Hello, Proedu!
startswith() and endswith() – Check Prefix and Suffix
# startswith() and endswith() - Check Prefix and Suffix: word = "Hello, Proedu!" starts_with_hello = word.startswith("Hello") ends_with_Proedu = word.endswith("Proedu!") print("Starts with 'Hello':", starts_with_hello) print("Ends with 'Proedu!':", ends_with_Proedu) # Output: Starts with 'Hello': True Ends with 'Proedu!': True
isalpha() – Check if All Characters are Alphabetic
# isalpha() - Check if All Characters are Alphabetic: word = "HelloProedu" is_alpha = word.isalpha() print("Is alphabetic:", is_alpha) #Output: Is alphabetic: True
isdigit() – Check if All Characters are Digits
# isdigit() - Check if All Characters are Digits: word = "12345" is_digit = word.isdigit() print("Is digit:", is_digit) #Output: Is digit: True
isalnum() – Check if All Characters are Alphanumeric
# isalnum() - Check if All Characters are Alphanumeric: word = "Hello123" is_alphanumeric = word.isalnum() print("Is alphanumeric:", is_alphanumeric) #Output: Is alphanumeric: True
isspace() – Check if All Characters are Whitespace
# isspace() - Check if All Characters are Whitespace: word = " " is_space = word.isspace() print("Is space:", is_space) #Output: Is space: True
join() – Concatenate Elements of an Iterable
# join() - Concatenate Elements of an Iterable: words = ["Hello", "Proedu", "!"] joined_string = " ".join(words) print("Joined String:", joined_string) #Output: Joined String: Hello Proedu !
split() – Split a String into a List
# split() - Split a String into a List: word = "Hello, Proedu!" split_list = word.split(", ") print("Split List:", split_list) #Output: Split List: ['Hello', 'Proedu!']
startswith() and endswith() with Tuple of Prefixes/Suffixes
# startswith() and endswith() with Tuple of Prefixes/Suffixes: word = "Hello, Proedu!" starts_with_hello_or_hi = word.startswith(("Hello", "Hi")) ends_with_Proedu_or_universe = word.endswith(("Proedu!", "Universe")) print("Starts with 'Hello' or 'Hi':", starts_with_hello_or_hi) print("Ends with 'Proedu!' or 'Universe':", ends_with_Proedu_or_universe) #Output: Starts with 'Hello' or 'Hi': True Ends with 'Proedu!' or 'Universe': True
index() – Find Substring (Raises ValueError if not found)
# index() - Find Substring (Raises ValueError if not found): word = "Hello, Proedu!" index = word.index("Proedu") print("Index of 'Proedu':", index) #Output: Index of 'Proedu': 7
rfind() – Find Substring from the Right (Returns Index)
# rfind() - Find Substring from the Right (Returns Index): word = "Hello, Proedu! Proedu!" last_index = word.rfind("Proedu") print("Last Index of 'Proedu':", last_index) #Output: Last Index of 'Proedu': 15
partition() – Split the String at the First Occurrence of a Separator
# partition() - Split the String at the First Occurrence of a Separator: word = "apple,orange,banana" head, separator, tail = word.partition(",") print("Head:", head) print("Separator:", separator) print("Tail:", tail) #Output: Head: apple Separator: , Tail: orange,banana
center() – Center a String within a Specified Width
# center() - Center a String within a Specified Width: word = "Hello" centered_string = word.center(10, "*") print("Centered String:", centered_string) #Output: Centered String: **Hello***
ljust() and rjust() – Left-justify or Right-justify a String within a Specified Width
word = "Hello" left_justified = word.ljust(10, "-") right_justified = word.rjust(10, "-") print("Left-justified:", left_justified) print("Right-justified:", right_justified) # Left-justified: Hello----- # Right-justified: -----Hello #
swapcase() – Swap Case of Characters (Lowercase to Uppercase and Vice Versa)
word = "Hello, Proedu!" swapped_case = word.swapcase() print("Swapped Case:", swapped_case) # Output: # Swapped Case: hELLO, pROEDU!
zfill() – Pad a Numeric String with Zeros on the Left
numeric_string = "42" zero_padded = numeric_string.zfill(5) print("Zero-padded:", zero_padded) # Output: # Zero-padded: 00042
casefold() – Perform Case-insensitive String Comparison
word = "Hello, Proedu!" casefolded_string = word.casefold() print("Casefolded String:", casefolded_string) # Output # Casefolded String: hello, proedu!
encode() and decode() – Encode and Decode Strings
word = "Hello, 你好" encoded_utf8 = word.encode('utf-8') decoded_utf8 = encoded_utf8.decode('utf-8') print("Encoded UTF-8:", encoded_utf8) print("Decoded UTF-8:", decoded_utf8) # Output: # Encoded UTF-8: b'Hello, \xe4\xbd\xa0\xe5\xa5\xbd' # Decoded UTF-8: Hello, 你好