Modification / Replace Methods in Python
Python provides several modification methods that return a modified version of the string based on certain operations. These operations include replacing characters, removing whitespace, splitting text, and joining strings.
These string methods help to change, clean, break, or join a string. They do not change the original string but return a new string.
1. replace() Method
Replaces all matching parts (substring) with a new part.
Syntax:
string.replace(old, new)
Example:
text = "Python is easy. Python is powerful."
updated = text.replace("Python", "Java")
print(updated)
Output:
Java is easy. Java is powerful.
Explanation:
- All "Python" words are replaced with "Java".
- Original string stays the same. New string is stored in
updated.
2. strip() Method
Removes spaces (or specified characters) from both ends of a string.
Syntax:
string.strip()
Note:
If no argument is given, it removes all spaces,
tabs, and newline characters from both sides.
Example:
line = " Shiksha Sanchar "
cleaned = line.strip()
print(cleaned)
Output:
Shiksha Sanchar
Explanation:
- There were extra spaces on both sides of the string.
strip()removed those spaces but not the ones between the words.
3. lstrip() Method
Removes spaces only from the left side.
Syntax:
string.lstrip()
Example:
msg = " Hello!"
left_clean = msg.lstrip()
print(left_clean)
Output:
Hello!
4. rstrip() Method
Removes spaces only from the right side.
Syntax:
string.rstrip()
Example:
msg = "Hello! "
right_clean = msg.rstrip()
print(right_clean)
Output:
Hello!
5. split() Method
Breaks the string into parts and gives a list.
Syntax:
string.split(separator)
Note:
If no separator is given, it uses space by default.
Example:
line = "Shiksha Sanchar is helpful"
words = line.split()
print(words)
Output:
['Shiksha', 'Sanchar', 'is', 'helpful']
Explanation:
- The string is split wherever there is space.
- Result is a list of words.
6. join() Method
Joins list items into one string using a separator.
Syntax:
separator.join(list)
Example:
words = ["Learn", "with", "ShikshaSanchar"]
sentence = " ".join(words)
print(sentence)
Output:
Learn with ShikshaSanchar
Explanation:
- List elements are joined with space in between.
- You can use any separator like
"-","+", etc.
String Replace / Modification Methods : Summary table
| Method | Description |
|---|---|
replace(old, new) |
Replaces old part with new part in the string. |
strip() |
Removes spaces from both sides (left + right). |
lstrip() |
Removes spaces from the left side only. |
rstrip() |
Removes spaces from the right side only. |
split() |
Breaks the string into parts and gives a list. |
join() |
Joins items of a list into one string. |