remove string from string python – How to remove specific substrings from a set of strings in Python?

remove string from string python – Using string replace() function and Using string translate() function Example.

remove string from string python

remove string from string python: There are main 5 Ways to Remove a Character from String in Python By using Naive method, By using replace() function, By using slice and concatenation, By using join() and list comprehension and By using translate() method.

You can enroll in Python Course to learn the language in detail.

Python Remove Character from String using replace()

Example

>>> x = 'Pakainfo.great'
>>> y = x.replace('.great','')
>>> y
'Pakainfo'
>>> x
'Pakainfo.great'

str = 'abc12321cba'

print(str.replace('a', ''))

Python Remove Character from String using translate()

Example

str = 'abc12321cba'

print(str.translate({ord('a'): None}))

Removing Spaces from a String

Example

str = ' 9 8 7 6 '
print(str.replace(' ', '')) # 9876
print(str.translate({ord(i): None for i in ' '})) # 9876

Python Remove newline from String

Example

str = 'ab\ncd\nef'
print(str.replace('\n', ''))
print(str.translate({ord('\n'): None}))

Don’t Miss : Remove Substring From String Python

Read Also:  convert string to array python

Remove substring from string

Example

str = 'ab12abc34ba'
print(str.replace('ab', ''))

Remove specified number of times

Example

str = 'abababab'
print(str.replace('a', 'A', 2))

I hope you get an idea about remove string from string python.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.