【问题标题】:Why can't word.lstrip be assigned to function call?为什么不能将 word.lstrip 分配给函数调用?
【发布时间】:2025-12-11 07:35:01
【问题描述】:
def pig_latin(text):
  say = ""
  # Separate the text into words
  words = text.split()
  for word in words:
    # Create the pig latin word and add it to the list
    word.lstrip(-1) += (word[0]+"ay")
    say.append(word)
    # Turn the list back into a phrase
  return say
        
print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay"
print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"

在 word.lstrip 上遇到语法错误。我可以找到答案 here 我只需要知道我对 .lstrip 甚至可能是 for 循环不了解的地方..

【问题讨论】:

  • word.lstrip(-1) 不是lvalue 所以不能在+= 左边使用将是你的下一个错误

标签: python


【解决方案1】:

" hi ".lstrip(-1) 在我的机器上返回此错误:TypeError: lstrip arg must be None or str

" hi ".lstrip() 返回'hi '

"tttthi ".lstrip("t") 返回'hi '

lstrip() 方法只接受字符串参数或根本不接受参数。您提供了一个整数参数,这就是它出错的原因。

【讨论】: