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

Python017

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

去除不想要的字符有很多种方法

1、利用python中的replace()方法,把不想要的字符替换成空;

2、利用python的rstrip()方法,lstrip()方法,strip()方法去除收尾不想要的字符。

用法如下:

Python3 replace()方法

Python3 rstrip()方法  

Python3 lstrip()方法