【问题标题】:Python-My string variable won't add up into one stringPython-我的字符串变量不会加起来成一个字符串
【发布时间】:2020-02-14 10:57:10
【问题描述】:

我似乎在将字符串添加在一起时遇到问题。
我写了一个函数,我一直调用它来解码或编码一个字符串。
问题是当我打印结果时,它只能打印一个字符,而不是整个代码。
在函数之外,此方法通过在字母后添加字母来工作。
这里我使用数字。

def code(s,i):
  result = ""
  if i < len(s):
    if s[i] == '0':
      result += "3"
      print (result)
      code(s,i+1)
    if s[i] == '1':
      result += "4"
      print (result)
      code(s,i+1)
    else:
      print ("An Error seems to have occured.")
  else:
    print("Code is done.")
  return

例如,如果我输入:01
我期望结果:3
34
但它只打印:3
4
所以基本上重播后的结果删除/覆盖了之前字符串中的内容。
我想在一个字符串中打印结果,而不是一行一行地打印结果。
这只是我缩短的代码的一部分。为什么结果不加起来?
这是我定义的输入方式。
entered = input("Please type something.")

【问题讨论】:

  • 这段代码应该做什么?你希望你没有看到什么行为?
  • 你的问题很难理解,你想达到什么目标,即 s 和 i 的值是多少?你得到什么输出?你期待什么输出?请edit您的问题并添加一些详细信息。

标签: python string variables add


【解决方案1】:

实际上您的代码是正确的,但只有一个问题是,在通过第一个嵌套 if 子句后,代码进一步进入下一个,它进入嵌套 else 子句。

要停止这种情况,您必须返回程序

你应该这样编写代码。

def code(s,i):
  result = ""
  if i < len(s):
    if s[i] == '0':
      result += "3"
      print (result)
      code(s,i+1)
      return
    if s[i] == '1':
      result += "4"
      print (result)
      code(s,i+1)
      return
    else:
      print ("An Error seems to have occured.")
  else:
    print("Code is done.")
  return

【讨论】:

  • 谢谢,这已经把错误信息带走了。
【解决方案2】:

我找到了解决问题的方法。
每次我回忆起它重置我的代码的功能,所以我将结果作为 我的函数参数:

def code(s,i,result):

  if i < len(s):
    if s[i] == '0':
      result += "3"
      print (result)
      code(s,i+1,result)
      return
    if s[i] == '1':
      result += "4"
      print (result)
      code(s,i+1,result)
      return
    else:
      print ("An Error seems to have occured.")
  else:
    print("Code is done.")
  return

现在结果打印出我需要的内容,感谢您的帮助! ^^

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 2020-04-28
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多