温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何去掉字符串中不需要的字符

发布时间:2020-03-05 09:46:28 来源:网络 阅读:139 作者:rdu74r574 栏目:编程语言

如何去掉字符串中不需要的字符

如何去掉字符串中不需要的字符

# 方法一
s = '  abc  123             '
print s.strip()  # 去掉两端的空格
print s.lstrip()  # 去掉左端的空格
print s.rstrip()  # 去掉右端的空格

s = '---abc+++'
print s.strip('-+')  # abc

# 方法二
s = 'abc:123'
print s[:3] + s[4:]  # abc123

# 方法三
# 只能替换单个字符
s = '\tabc\t123\txyz'
print s.replace('\t', '')  # abc123xyz
# 可以替换多个不同字符
import re
s = '\tabc\t123\txyz\rwe\r'
print re.sub('[\t\r]', '', s)  # abc123xyzwe

#方法四
# 将abc替换成xyz,将xyz替换成abc,做成一个加密的效果
import string
s = 'abc1234324xyz'
print s.translate(string.maketrans('abcxyz', 'xyzabc'))  #xyz1234324abc

s = 'abc\refg\n234\t'
print s.translate(None, '\t\r\n')  # abcefg234


# unicode 字符串

u = u'ni\u0301 ha\u030c, chi\u0304 fa\u0300n'
print u.translate({0x0301: None})  # ni hǎ, chī fàn  去掉了ni 上面的音调符号
print u.translate(dict.fromkeys([0x0301, 0x030c, 0x0304, 0x0300]))  # ni ha, chi fan  去掉了所有的音调符号







向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI