我试图创建一个函数来替换给定字符串中的某些值,但收到以下错误: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)
您可以通过使用
regex
模块的更简单的解决方案来实现这一点。定义一个匹配任何MMM/
或/TTT
的模式,并将其替换为''
。在在你的功能中它看起来像
^{pr2}$rstrip
方法将删除字符串末尾的/
(如果有的话)。(不需要if)。在用字符串中搜索的所有模式构建模式。使用
(pattern)?
可以将模式定义为可选的。你想说多少就说多少。在它比串联字符串操作更易读。在
注意这个
rstrip
方法将删除所有的尾随斜杠,而不仅仅是一个。如果只想删除最后一个字符,则需要If语句:if语句使用对字符串的索引访问,-1表示最后一个字符。分配是通过切片进行的,直到最后一个字符为止。在
相关问题 更多 >
编程相关推荐