首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用"string.strip()“

使用"string.strip()“
EN

Stack Overflow用户
提问于 2016-10-27 02:22:08
回答 2查看 90关注 0票数 1

我尝试使用".strip()“删除字符串中的所有标点符号,但不起作用

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2016-10-27 04:30:16

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

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

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2016-10-30 22:55:10

string.strip不会像Sondering给出的那样工作,但你可以使用string.punctuation和生成器表达式:

代码语言:javascript
复制
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'
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40269545

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档