本文介绍了Python .strip 方法不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样开头的函数:
I have a function that begins like this:
def solve_eq(string1):
string1.strip(' ')
return string1
我正在输入字符串 '1 + 2 * 3 ** 4' 但 return 语句根本没有去除空格,我不知道为什么.我什至试过 .replace() 没有运气.
I'm inputting the string '1 + 2 * 3 ** 4' but the return statement is not stripping the spaces at all and I can't figure out why. I've even tried .replace() with no luck.
推荐答案
Strip 不会删除任何地方的空格,只会删除开头和结尾的空格.试试这个:
Strip does not remove whitespace everywhere, only at the beginning and end. Try this:
def solve_eq(string1):
return string1.replace(' ','')
在这种情况下使用 strip()
是多余的(显然,感谢评论员!).
Using strip()
in this case is redundant (obviously, thanks commentators!).
附言在我休息之前奖励有用的片段(感谢 OP!):
P.s. Bonus helpful snippet before I take my SO break (thanks OP!):
import re
a_string = re.sub(' +', ' ', a_string).strip()
这篇关于Python .strip 方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!