【问题标题】:Failing to assign value to variable in a defined function未能在定义的函数中为变量赋值
【发布时间】: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


    【解决方案1】:

    您当前的版本失败,因为创建后无法修改字符串(见注释);而是执行以下操作:

    amended_str = normalize_str(orig_str)
    

    你想要的缩短版是:

    def normalize_str(in_str):
        return in_str.replace(' ', '').replace('-', '')
    
    # Or
    normalize_str = lambda s: s.replace(' ', '').replace('-', '')
    

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

    【讨论】:

      【解决方案2】:

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

      #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"
      

      【讨论】:

        【解决方案3】:

        字符串是不可变的对象,这意味着在 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
        

        【讨论】:

        • OP 也想替换内部空间(我一开始也是这样,哈哈)
        猜你喜欢
        • 2020-09-16
        • 1970-01-01
        • 2018-06-09
        • 1970-01-01
        • 2013-07-13
        • 2013-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多