首页 > 解决方案 > 如何删除逗号,形成python程序

问题描述

我想删除我的计数器应用程序在每行末尾的逗号。我已经尝试过 r.strip 的东西,但我不确定如何正确使用它。

回复链接:回复

def counter(start, stop):
  x = start
  if start > stop:
      return_string = "Counting down: "
      while x >= stop:
          return_string += str(x)
          x = x-1
          if start != stop:
              return_string += ","
  else:
      return_string = "Counting up: "
      while x <= stop:
          return_string += str(x)
          x = x + 1
          if start != stop:
              return_string += ","

  return return_string

print(counter(1, 10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10"
print(counter(2, 1)) # Should be "Counting down: 2,1"
print(counter(5, 5)) # Should be "Counting up: 5"

谢谢。

标签: pythoncounter

解决方案


如果您想更正代码,可以稍微更改条件以调整逗号的添加方式(尽管有许多奇特的方法可以写得更好):

def counter(start, stop):
  x = start
  if start > stop:
      return_string = "Counting down: "
      while x >= stop:
          return_string += str(x)
          x = x-1
          if x != stop-1:
              return_string += ","
  else:
      return_string = "Counting up: "
      while x <= stop:
          return_string += str(x)
          x = x + 1
          if x != stop+1:
              return_string += ","

  return return_string

或者以一种快速的方式,您可以替换这行代码:

return return_string

和:

return return_string.rstrip(',')

推荐阅读