python - 去除字符串中特定字符

Python015

python - 去除字符串中特定字符,第1张

一、去掉字符串两端字符: strip(), rstrip(), lstrip()

s.strip()    # 删除两边(头尾)空字符,默认是空字符

s.lstrip()    # 删除左边头部空字符

s.rstrip()    # 删除右边尾部空字符

s.strip('+-')    # 删除两边(头尾)加减字符

s.strip('-+').strip()   # 删除两边(头尾)加减和空字符

s.strip('x')    # 删除两边特定字符,例如x

二、去掉字符串中间字符: replace(), re.sub()

# 去除\n字符

s = '123\n'

s.replace('\n', '')

import re

# 去除\r\n\t字符

s = '\r\nabc\t123\nxyz'

re.sub('[\r\n\t]', '', s)

三、转换字符串中的字符:translate()

s = 'abc123xyz'

# a <->  x, b <-> y, c <->z,建立字符映射关系

str.maketrans('abcxyz', 'xyzabc')

# translate把其转换成字符串

print(s.translate(str.maketrans('abcxyz', 'xyzabc')))

参考链接:

https://blog.csdn.net/weixin_41738417/article/details/103267728

这个明显是错误的,你根本没理解replace函数是怎么用的。

Python str.replace(old, new[, max])

方法把字符串str中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max

次。

如果非要用replace()函数来实现要这样写:

import string

m = l

for c in string.punctuation:  

    m = m.replace(c,")

更简便的方法是用translate(),代码如下:

import string

m = l.translate(None, string.punctuation)