问题描述
我是python(和这个社区)的新手,这是一个很久以前从here提出并回答的问题的分支。
列表如下:
[[noreturn]]
创建不带标点的新列表x(并删除空元素)将是:
['hello','...','h3.a','ds4,']
输出:
x = [''.join(c for c in s if c not in string.punctuation) for s in x]
x = [s for s in x if s]
print(x)
但是,我如何只能从每个元素的开头和结尾删除所有标点符号?我的意思是改为输出:
['hello','h3a','ds4']
在这种情况下,请将句号保留在h3a中,但在ds4的末尾删除逗号。
解决方法
您可以使用正则表达式。 re.sub()
可以用字符串替换正则表达式的所有匹配项。
import re
X = ['hello','.abcd.efg.','h3.a','ds4,']
X_rep = [re.sub(r"(^[^\w]+)|([^\w]+$)","",x) for x in X]
print(X_rep)
# Output: ['hello','abcd.efg','ds4']
正则表达式的解释:Try it
-
(^[^\w]+)
:-
^
:字符串的开头 -
[^\w]+
:一个或多个非单词字符
-
-
|
:上一个表达式或下一个表达式 -
([^\w]+$)
:-
[^\w]+
:一个或多个非单词字符 -
$
:字符串结尾
-
x = ['hello','...',']
x[0] = [''.join(c for c in s if c not in string.punctuation) for s in x][0]
x[(len(x)-1)] = [''.join(c for c in s if c not in string.punctuation) for s in x][(len(x)-1)]
x = [s for s in x if s]
print(x)