【发布时间】:2020-10-26 20:49:09
【问题描述】:
我正在尝试定义一个从字符串中去除空格和连字符的函数,例如它将foo - bar 编辑为foobar。
原始字符串应存储在命名变量下(例如orig_str),修改后的字符串应存储在新变量名下(例如amended_str)。
我试图定义这样一个函数根本没有做任何事情。
#This is what my function looks like
def normalise_str(old_string, new_string): #def func
temp_string = old_string.replace(" ", "") #rm whitespace
temp_string = temp_string.replace("-", "") #rm hyphens
new_string = temp_string #assign newly modified str to var
#This is what I would like to achieve
orig_str = "foo - bar"
normalise_str = (orig_str, amended_str)
print(amended_str) #I would like this to return "foobar"
我肯定会重视一个更有效的解决方案......
amended_str = orig_str.replace(" " and "-", "") #I'm sure something sensible like this exists
但是,我需要了解我的功能做错了什么,以促进我的学习。
【问题讨论】:
标签: python python-3.x string function replace