python逗号代码,Python - 用逗号分隔列表

I am writing a piece of code that should output a list of items separated with a comma. The list is generated with a for loop. I use the

for x in range(5):

print(x, end=",")

The problem is I don't know how to get rid of the last comma that is added with the last entry in the list. It outputs this:

0,1,2,3,4,

How do I remove the ending ' , ' ?

解决方案

Pass sep="," as an argument to print()

You are nearly there with the print statement.

There is no need for a loop, print has a sep parameter as well as end.

>>> print(*range(5), sep=", ")

0, 1, 2, 3, 4

A little explanation

The print builtin takes any number of items as arguments to be printed. Any non-keyword arguments will be printed, separated by sep. The default value for sep is a single space.

>>> print("hello", "world")

hello world

Changing sep has the expected result.

>>> print("hello", "world", sep=" cruel ")

hello cruel world

Each argument is stringified as with str(). Passing an iterable to the print statement will stringify the iterable as one argument.

>>> print(["hello", "world"], sep=" cruel ")

['hello', 'world']

However, if you put the asterisk in front of your iterable this decomposes it into separate arguments and allows for the intended use of sep.

>>> print(*["hello", "world"], sep=" cruel ")

hello cruel world

>>> print(*range(5), sep="---")

0---1---2---3---4

Using join as an alternative

The alternative approach for joining an iterable into a string with a given separator is to use the join method of a separator string.

>>>print(" cruel ".join(["hello", "world"]))

hello cruel world

This is slightly clumsier because it requires non-string elements to be explicitly converted to strings.

>>>print(",".join([str(i) for i in range(5)]))

0,1,2,3,4

Brute force - non-pythonic

The approach you suggest is one where a loop is used to concatenate a string adding commas along the way. Of course this produces the correct result but its much harder work.

>>>iterable = range(5)

>>>result = ""

>>>for item, i in enumerate(iterable):

>>> result = result + str(item)

>>> if i > len(iterable) - 1:

>>> result = result + ","

>>>print(result)

0,1,2,3,4

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值