使用" string.strip()"

时间:2016-10-26 18:22:08

标签: python string strip

我正在尝试使用" .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

2 个答案:

答案 0 :(得分:1)

Strip仅从字符串的开头和结尾删除。由于您希望更改整个字符串中的标点符号,因此strip不起作用。

您始终可以在字符串的末尾使用strip作为标点符号,然后使用list comprehension在字符串中搜索其他标点符号实例。或者也许构建一个从第一个索引到最后一个索引的新字符串,只包含不是标点符号的值:

result = ""
punctuation = ["!@#$%^&*()'-_+={}[]|\:;'<>?,./\"")**]
for character in sentence:
    same = False
    for punc in punctuation:
        if punc == character:
            same = True
    if not same:
        result += i
return result

答案 1 :(得分:0)

string.strip因Sondering Narcissist提供的原因无效,但您可以将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'