更换和剥离功能

2024-06-01 11:46:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个函数来替换给定字符串中的某些值,但收到以下错误:EOL while scanning single-quoted string.

不知道我做错了什么:

 def DataClean(strToclean):
        cleanedString = strToclean
        cleanedString.strip()
        cleanedString=  cleanedString.replace("MMMM/", "").replace("/KKKK" ,"").replace("}","").replace(",","").replace("{","")
        cleanedString = cleanedString.replace("/TTTT","")
        if cleanedString[-1:] == "/":
           cleanedString = cleanedString[:-1]

        return str(cleanedString)

Tags: 函数字符串stringdef错误replacestripsingle
1条回答
网友
1楼 · 发布于 2024-06-01 11:46:33

您可以通过使用regex模块的更简单的解决方案来实现这一点。定义一个匹配任何MMM//TTT的模式,并将其替换为''。在

import re

pattern = r'(MMM/)?(/TTT)?'

text = 'some text MMM/ and /TTT blabla'
re.sub(pattern, '', text)
# some text and blabla

在你的功能中它看起来像

^{pr2}$

rstrip方法将删除字符串末尾的/(如果有的话)。(不需要if)。在

用字符串中搜索的所有模式构建模式。使用(pattern)?可以将模式定义为可选的。你想说多少就说多少。在

它比串联字符串操作更易读。在

注意这个rstrip方法将删除所有的尾随斜杠,而不仅仅是一个。如果只想删除最后一个字符,则需要If语句:

if new_str[-1] == '/':
    new_str = new_str[:-1]

if语句使用对字符串的索引访问,-1表示最后一个字符。分配是通过切片进行的,直到最后一个字符为止。在

相关问题 更多 >