如何去掉逗号,形成python程序
How to remove comma, form python program
我想删除我的计数器应用程序在每行末尾的逗号。我试过 r.strip 东西,但我不确定如何正确使用它。
REPL LINK: repl
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"
谢谢。
如果您想更正您的代码,您可以稍微更改您的条件以调整逗号的添加方式(尽管有许多奇特的方式您可以写得更好):
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(',')
我想删除我的计数器应用程序在每行末尾的逗号。我试过 r.strip 东西,但我不确定如何正确使用它。
REPL LINK: repl
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"
谢谢。
如果您想更正您的代码,您可以稍微更改您的条件以调整逗号的添加方式(尽管有许多奇特的方式您可以写得更好):
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(',')