Modifying Strings in python

Modifying Strings in python

Problem: Explain the methods and techniques available in Python for modifying strings. Provide examples of how to perform common string operations such as concatenation, slicing, replacing, and converting to uppercase/lowercase.
Solution:Python provides various methods and techniques for modifying strings. Here are some common operations:
Concatenation:
You can combine two or more strings using the + operator.
strl = " Hello" 
str2 = " World" 
result = strl + str2
print (result) # " Hello World" 
Uppercase and Lowercase:
You can convert a string to uppercase or lowercase using the upper() and lower() methods.
word = " Hello"
upper_word = word.upper( )
lower_word = word.lower( )
print (upper_word) # " HELLO" 
print (lower_word) # " hello"
Replacing:
You can replace substrings within a string using the replace() method.
sentence ="I love programming in Python."
modified =sentence.replace("Python" , "Java" )
print (modified) # " I love programming in Java . "
Slicing:
You can extract a portion of a string usi ng slicing. Slicing uses the format [start:end], where start is inclusive, and end is exclusive.
text = " Python is awesome" 
sliced = text[7 : 10]
print (sliced) # " is "
String Interpolation:
You can modify strings by inserting variables using fstrings (Python 3.6+).
word = " Hello" 
upper_word = word.upper() 
lower_word = word.lower() 
print(upper_word) # " HELLO" 
print(lower_word) # " hello"
Stripping Whitespace:
You can remove leading and trailing whitespace using strip(), lstrip(), and rstrip().
text = "This is a sentence with whitespace ."
stripped_text = text.strip()
print (stripped_text) # " This is a sentence with whitespace ."

More Questions


15 . Modifying Strings in Python
16 . Built-in Types
17 . Linear (Sequential) Search and Its Usage in Python
18 . Benefits of Python
19 . Discussing Data Types
20 . Local and Global Variables
21 . Checking if a List is Empty
22 . Creating a Chain of Function Decorators
23 . New features added in Python 3.9.0.0 version
24 . Memory management in Python
25 . Python modules and commonly used built-in modules