Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String python3:从一个长链.replace().replace().replace()的字符串中删除几个字符_String_Methods_Python 3.x - Fatal编程技术网

String python3:从一个长链.replace().replace().replace()的字符串中删除几个字符

String python3:从一个长链.replace().replace().replace()的字符串中删除几个字符,string,methods,python-3.x,String,Methods,Python 3.x,我在堆栈溢出上找到了这个示例。我理解,但对于这样一个简单的方法概念来说似乎有点过分。。。从字符串中删除几个字符 import string exclude = set(string.punctuation) s = ''.join(ch for ch in s if ch not in exclude) 导入字符串 排除=设置(字符串.标点符号) s=''.join(如果ch不在排除中,则ch代表ch在s中) python 3.1中是否有一个内置的字符串方法来完成以下工作: s = "a,b,c

我在堆栈溢出上找到了这个示例。我理解,但对于这样一个简单的方法概念来说似乎有点过分。。。从字符串中删除几个字符

import string exclude = set(string.punctuation) s = ''.join(ch for ch in s if ch not in exclude) 导入字符串 排除=设置(字符串.标点符号) s=''.join(如果ch不在排除中,则ch代表ch在s中) python 3.1中是否有一个内置的字符串方法来完成以下工作:

s = "a,b,c,d,e,f,g,h,i" s = s.strip([",", "d", "h"]) s=“a、b、c、d、e、f、g、h、i” s=s.strip([“,”,“d”,“h”]) 而不是:

s = s.replace(",", "").replace("d", "").replace("h", "") s=s.replace(“,”,”).replace(“,”).replace(“,”)
我不同意你发现的例子过于复杂。对于您的用例,该代码将变成:

s = ''.join(ch for ch in s if ch not in ",dh")
这对我来说似乎很简洁。但是,还有一种替代方法,它更简洁,可能更有效:

s = s.translate(str.maketrans("", "", ",dh"))
免责声明:由于我没有访问Python3.1解释器的权限,所以我没有实际测试这段代码。Python 2.6(我已经测试过)中的等价物是:

t = ''.join(chr(i) for i in range(256))
s = s.translate(t, ",dh")