简体   繁体   English

如何在 python 字符串格式中仅添加不带括号的列表值

[英]How to add only values of list without brackets in python string formatting

In the code below, how can I remove the brackets in the output?在下面的代码中,如何删除 output 中的括号?

In [11]: xx = [1,2,3,4]

In [12]: print('%s BLAH' %xx)
[1, 2, 3, 4] BLAH

I would like the output to be:我希望 output 是:

1, 2, 3, 4 BLAH

I am looking for a general solution, NOT something like below (I want to use %s only once):我正在寻找一个通用的解决方案,而不是像下面这样的(我只想使用%s一次):

print('%s %s %s %s BLAH' %tuple(xx))

You have to join the list to a string:您必须将列表加入字符串:

print('%s BLAH' % ', '.join(xx))

Straightforward way would be to use join()直接的方法是使用join()

>>> a
[1, 2, 3, 4]
>>> ', '.join([str(x) for x in a])
'1, 2, 3, 4'
>>> 

If you want to not use join then override the str dunder function of the list class.如果您不想使用连接,则覆盖列表 class 的 str dunder function。 Please see below:请看下面:

class FancyList(list):
    def __repr__(self):
        fancy_output = ''
        for item in self:
            fancy_output += f'{item}, '
        return fancy_output.strip().strip(',')

    def __str__(self):
        return self.__repr__()

if __name__ == "__main__":
    a = [1,2,3,4]
    print(a)
    fancy_a = FancyList(a)
    print(fancy_a)
    print('%s BLAH' % fancy_a)
    fancy_a.append(100)
    print(fancy_a)
    print('%s BLAH' % fancy_a)

which gives me output:这给了我 output:

[1, 2, 3, 4]
1, 2, 3, 4
1, 2, 3, 4 BLAH
1, 2, 3, 4, 100
1, 2, 3, 4, 100 BLAH

You actually can do it without %s with this code:实际上,您可以使用以下代码在没有 %s 的情况下做到这一点:

print(', '.join(xx) + " BLAH")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM