温馨提示×

温馨提示×

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

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

python如何删除字符串中指定字符

发布时间:2021-04-21 10:18:37 来源:亿速云 阅读:347 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关python如何删除字符串中指定字符的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

python是什么意思

Python是一种跨平台的、具有解释性、编译性、互动性和面向对象的脚本语言,其最初的设计是用于编写自动化脚本,随着版本的不断更新和新功能的添加,常用于用于开发独立的项目和大型项目。

import re 
temp = "司法局让我和户 1 5. 8 0. !!?? 客户维护户外" 
temp = temp.decode("utf8") 
string = re.sub("[\s+\.\!\/_,$%^*(+\"\']+|[+——!,。?、~@#¥%……&*()]+".decode("utf8"), "".decode("utf8"),temp) 
print string

或者是这样的

'''引入string模块'''
import string
'''使用标点符号常量'''
string.punctuation
text = "*/@》--【】--12()测试*()"

'''去除字符串中所有的字符,可增加自定义字符'''
def strclear(text,newsign=''):
  import string # 引入string模块
  signtext = string.punctuation + newsign # 引入英文符号常量,可附加自定义字符,默认为空
  signrepl = '@'*len(signtext) # 引入符号列表长度的替换字符
  signtable = str.maketrans(signtext,signrepl) # 生成替换字符表
  return text.translate(signtable).replace('@','') # 最后将替换字符替换为空即可

strclear(text,'》【】')

我一开始用的后面的这个,着实是有点暴力,于是找了查了一下原文档,发现python3中完全有更好的方法去实现这样的功能(似乎是新更新的?不太清楚,我的是python最新版本3.6.6)

和上面的方法一样是利用的是str的translate()和maketrans()

translate()自然不用说这里的重点是maketrans(),先放上官方的文档

static str.maketrans(x[, y[, z]])
This static method returns a translation table usable for str.translate().

If there is only one argument, 
it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, 
strings (of arbitrary lengths) or None. Character keys will then be converted to ordinals.

If there are two arguments, 
they must be strings of equal length, 
and in the resulting dictionary, 
each character in x will be mapped to the character at the same position in y. 
If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

可以看出maketrans是可以放三个参数的(以前一直以为只有两个....)

前两个参数是需要一一对应进行替换,需要字符串长度相同

第三个参数是直接替换为None

这里就直接上代码了

import string

i = 'Hello, how are you!'

i.translate(str.maketrans('', '', string.punctuation))
>>>'Hello how are you'

 i = 'hello world i am li'
 i.translate(str.maketrans('','','l'))

>>>'heo word i am i'

这里的string.punctuation 是python内置的标点符号的合集

感谢各位的阅读!关于“python如何删除字符串中指定字符”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

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

AI