我尝试使用".strip()“删除字符串中的所有标点符号,但不起作用
sentence = "The sunset sets at twelve o' clock."
new_sentence = sentence.strip("!@#$%^&*()'-_+={}[]|\:;'<>?,./\"")**
print(new_sentence)
#result : The sunset sets at twelve o' clock
#Expectation : The sunset sets at twelve o clock发布于 2016-10-27 04:30:16
string仅从字符串的开头和结尾删除。由于您希望更改整个字符串中的标点符号,因此string将不起作用。
您始终可以在字符串的末尾使用string作为标点符号,然后使用列表理解在字符串中搜索其他标点符号实例。或者构建一个从第一个索引到最后一个索引的新字符串,其中只包含不是标点符号的值:
result = ""
punctuation = ["!@#$%^&*()'-_+={}[]|\:;'<>?,./\"")**]
for character in sentence:
same = False
for punc in punctuation:
if punc == character:
same = True
if not same:
result += i
return result发布于 2016-10-30 22:55:10
string.strip不会像Sondering给出的那样工作,但你可以使用string.punctuation和生成器表达式:
import string
def stripped(s, chars):
return ''.join(c for c in s if c not in chars)
sentence = "The sunset sets at twelve o' clock."
stripped(sentence, string.punctuation)
# 'The sunset sets at twelve o clock'https://stackoverflow.com/questions/40269545
复制相似问题