Remove specified characters from a string in python

Remove specific characters in a string (but only the specified characters at the beginning and end):

a = '你好\n我是xx。\n\n\n'
print(a.strip('\n'))

# 你好
# 我是xx。

To remove intermediate characters, use the replace() function:

a = '你好\n我是xx。\n\n\n'
print(a.replace('\n', ''))

# 你好我是xx。

Note:

replace(old, new[, max])

Basic usage: ss.replace(old, new[, max])

old is the character in the original string, new is the new string that needs to be replaced, max is the maximum number of matches, at most max times from left to right when matching. In general, the value of max is not set, and all are replaced by default.

a = 'old old string'
print(a.replace('old', 'new', 1))

# new old string

More: a.lstrip() removes the specified characters at the beginning of the ss string, a.rstrip() removes the specified characters at the end of ss

Guess you like

Origin blog.csdn.net/qq_45100200/article/details/131958708