python - 如何删除逗号,形成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"
谢谢。
解决方案
如果您想更正代码,可以稍微更改条件以调整逗号的添加方式(尽管有许多奇特的方法可以写得更好):
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(',')
推荐阅读
- sql - MS Access 查询,如何创建仅显示文件更改位置的最近日期的文件库存查询
- html - 将登录面板移动到屏幕中心
- javascript - Promise 链接到可能已解决的 Promise
- testing - 是否可以让 GitHub 自述文件图像跟随重定向?
- visual-studio-code - vscode devcontainer定义中的自定义键绑定
- reactjs - 如何通过 D3 从 ReactJS 中删除之前的实例?
- c#-4.0 - 与 CMQC.MQSO_SET_CORREL_ID 等效的 IBM MQ XMS 选项是什么
- c++ - OpenGL:有没有办法只保留源和目标之间的最大值?
- facebook - 如何为非 App-Scoped User ID 建立永久且公开的 Facebook 个人资料照片 URL?
- visual-studio - VS2019 中的 Xamarin Forms Designer 其他外形尺寸