为了账号安全,请及时绑定邮箱和手机立即绑定

无法为已定义函数中的变量赋值

无法为已定义函数中的变量赋值

慕尼黑的夜晚无繁华 2024-01-15 17:05:17
我正在尝试定义一个从字符串中去除空格和连字符的函数,例如它将编辑foo - bar为foobar.原始字符串应存储在命名变量(例如orig_str)下,修改后的字符串应在新变量名(例如amended_str)下返回。我尝试定义这样一个函数根本没有做任何事情。#This is what my function looks likedef 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 achieveorig_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然而,我需要了解我的功能做错了什么,以促进我的学习。
查看完整描述

3 回答

?
RISEBY

TA贡献1856条经验 获得超5个赞

您当前的版本失败,因为字符串在创建后无法修改(请参阅注释);相反,执行以下操作:


amended_str = normalize_str(orig_str)

您想要的缩短版本是:


def normalize_str(in_str):

    return in_str.replace(' ', '').replace('-', '')


# Or

normalize_str = lambda s: s.replace(' ', '').replace('-', '')

注意:您无法修改作为参数传递的字符串,因为字符串是不可变的 - 这意味着一旦创建,它们就无法修改。


查看完整回答
反对 回复 2024-01-15
?
哔哔one

TA贡献1854条经验 获得超8个赞

字符串是不可变的对象,这意味着在Python中,函数外部的原始字符串不能被修改。因此,您需要显式返回修改后的字符串。


def normalise_str(old_string):          

    return old_str.replace(' ','').replace('-', '')


orig_str = "foo - bar"

amended_str = normalise_str(old_string)

print(amended_str) # Should print foobar


查看完整回答
反对 回复 2024-01-15
?
森栏

TA贡献1810条经验 获得超5个赞

您需要输入旧字符串,进行更改,然后将最终的临时字符串返回给变量。


#This is what my function looks like


def normalise_str(old_string):          #def func

    temp_string = old_string.replace(" ", "")       #rm whitespace

    temp_string = temp_string.replace("-", "")      #rm hyphens

    return temp_string                     #assign newly modified str to var


#This is what I would like to achieve


orig_str = "foo - bar"

s = normalise_str(orig_str)

print(s) #I would like this to return "foobar"


查看完整回答
反对 回复 2024-01-15
  • 3 回答
  • 0 关注
  • 42 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信