【问题标题】:Python: Recursively modifying strings [duplicate]Python:递归修改字符串
【发布时间】:2017-04-06 13:18:26
【问题描述】:

我的目标是递归修改一个字符串,如果它的长度大于 48 个字符,最后一个单词将被删除。如果/一旦字符串的长度不超过 48 个字符,则返回它。

这是我的尝试:

def checkLength(str):
  if len(str) > 48:
    str = str.rsplit(' ',1)[0]
    checkLength(str)
  else:
    return str

传递长度大于 48 个字符的字符串会产生空值。

在 Python 中实现这一点的正确方法是什么,为什么上述函数不能按预期工作?

【问题讨论】:

  • 另外,不要使用str作为变量名,它会隐藏内置类型。
  • 感谢您的提示!以后我会牢记这一点。

标签: python python-2.7 recursion


【解决方案1】:
def checkLength(my_str):
  if len(my_str) > 48:
    my_str = str.rsplit(' ',1)[0]
    # you must return the recursive call! 
    return checkLength(my_str)
  else:
    return my_str

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 2014-01-12
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多