Python .strip 方法不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40444787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python .strip method not working
提问by Lanier Freeman
I have a function that begins like this:
我有一个这样开头的函数:
def solve_eq(string1):
string1.strip(' ')
return string1
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.
我正在输入字符串 '1 + 2 * 3 ** 4' 但返回语句根本没有去除空格,我不知道为什么。我什至试过 .replace() 没有运气。
回答by Eugene
Strip does not remove whitespace everywhere, only at the beginning and end. Try this:
Strip 不会在任何地方删除空格,仅在开头和结尾删除。尝试这个:
def solve_eq(string1):
return string1.replace(' ','')
Using strip()
in this case is redundant (obviously, thanks commentators!).
strip()
在这种情况下使用是多余的(显然,感谢评论员!)。
P.s. Bonus helpful snippet before I take my SO break (thanks OP!):
Ps Bonus 在我休息之前的有用片段(感谢 OP!):
import re
a_string = re.sub(' +', ' ', a_string).strip()
回答by Marissa Novak
Strip doesn't change the original string since strings are immutable. You should set a return value to the stripped string or just return the stripped string.
Strip 不会更改原始字符串,因为字符串是不可变的。您应该为剥离的字符串设置一个返回值,或者只返回剥离的字符串。
Option 1
选项1
def solve_eq(string1):
string1 = string1.replace(' ', '')
return string1
Option 2
选项 2
def solve_eq(string1):
return string1.replace(' ', '')
edit:
instead of string1.strip(' ')
, use string1.replace(' ', '')
编辑:而不是string1.strip(' ')
,使用string1.replace(' ', '')
回答by Scott Hunter
strip
returns the stripped string; it does not modify the original string.
strip
返回剥离后的字符串;它不会修改原始字符串。