String manipulation is a crucial aspect of working with textual data in Python. Strings are sequences of characters and are immutable, meaning they cannot be changed after they are created. Python provides various string manipulation techniques to perform operations like slicing, concatenation, formatting, and utilizing built-in string methods to modify and manipulate strings efficiently.
# Slicing allows you to extract a substring from a string based on its indices.
text = "Hello, World!"
# Extract the substring "Hello"
substring1 = text[0:5]
# Extract the substring "World!"
substring2 = text[7:]
print(substring1) # Output: "Hello"
print(substring2) # Output: "World!"
# Concatenation is the process of combining two or more strings to create a new string.
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: "John Doe"
# String formatting allows you to construct dynamic strings by inserting values into placeholders.
name = "Alice"
age = 30
# Using f-string (Python 3.6+)
formatted_string1 = f"My name is {name} and I am {age} years old."
# Using str.format()
formatted_string2 = "My name is {} and I am {} years old.".format(name, age)
# Using % operator (old style)
formatted_string3 = "My name is %s and I am %d years old." % (name, age)
print(formatted_string1) # Output: "My name is Alice and I am 30 years old."
print(formatted_string2) # Output: "My name is Alice and I am 30 years old."
print(formatted_string3) # Output: "My name is Alice and I am 30 years old."
# Python provides a variety of built-in string methods for string manipulation.
text = "Hello, World!"
# Convert to uppercase
uppercase_text = text.upper()
# Convert to lowercase
lowercase_text = text.lower()
# Replace "Hello" with "Hi"
replaced_text = text.replace("Hello", "Hi")
# Split the string into a list of words
words = text.split()
# Find the index of "World" in the string
index = text.find("World")
# Count the occurrences of "l" in the string
count_l = text.count("l")
print(uppercase_text) # Output: "HELLO, WORLD!"
print(lowercase_text) # Output: "hello, world!"
print(replaced_text) # Output: "Hi, World!"
print(words) # Output: ['Hello,', 'World!']
print(index) # Output: 7
print(count_l) # Output: 3
To work on the exercises, follow these steps:
Input: "hello world, how are you?" Output: "Hello World, How Are You?"
Input: "Python is a popular programming language. Python is versatile and powerful." Output: {'Python': 2, 'is': 2, 'a': 1, 'popular': 1, 'programming': 1, 'language': 1, 'versatile': 1, 'and': 1, 'powerful': 1}
Input: "hello", Shift: 3 Output: "khoor"
Input: length = 12 Output: "aB2@yC#7zEf1"
Input: "Hello World" Output: "olleH dlroW"
Input: "aaabbcccddddeee" Output: "a3b2c3d4e3"
Input: "listen", "silent" Output: True