[英]Print f list items in one line
I would like to print the list in one line.我想在一行中打印列表。 I works with simple print, but it doesn´t work when it´sf print.我使用简单的打印,但它在打印时不起作用。 How could I do that, please?请问我该怎么做? Thank you谢谢
list = ["A", "B", "C"]
print(*[n for n in list], sep=", ")
print(f"Item was added: {*[n for n in nazvy]}")
l = ["A", "B", "C"]
print(', '.join(l))
print(f"Item was added: {', '.join(l)}")
Output Output
A, B, C
Item was added: A, B, C
NOTE: Try not to use in-built keywords as variable names.注意:尽量不要使用内置关键字作为变量名。 Eg: list
例如: list
Your code didn't work because f-string doesn't allow starred expression or unpacking.您的代码不起作用,因为 f-string 不允许星号表达式或解包。
Meanwhile同时
print(*[n for n in list], sep=", ")
worked because it translates to below due to list unpacking工作,因为它转换到下面由于列表拆包
print('A', 'B', 'C', sep=", ")
I'd suggest this:我建议这样做:
list = ["A", "B", "C"]
print(f'Item was added: {",".join(str(x) for x in list)}')
print(f'Item was added: {", ".join(str(x) for x in list)}')
as per accepted answer on this question: f-string syntax for unpacking a list with brace suppression根据对这个问题的公认答案: f-string syntax for unpacking a list with括号抑制
Use "end=" instead of "sep=";使用 "end=" 而不是 "sep=";
list = ["A", "B", "C"]
for x in list:
print(x, end=', ')
You can use *list
to send each value to print statement.您可以使用*list
将每个值发送到打印语句。 With this approach, you don't have to worry about converting data to string.使用这种方法,您不必担心将数据转换为字符串。
With that, you can just give有了这个,你可以给
mylist = ["A", "B", "C", 4, 5, 6]
print(*my_list, sep=", ")
The output of this will be: output 将是:
A, B, C, 4, 5, 6
If you want to use the fstring, you can also try giving:如果你想使用 fstring,你也可以尝试给出:
print(f'{*mylist,}')
The output of this will be: output 将是:
('A', 'B', 'C', 4, 5, 6)
Note here that it prints with brackets ()
.请注意,它使用方括号()
打印。
For more details about unpacking f-string, see the post on Stackoverflow here有关解压 f-string 的更多详细信息,请参阅此处Stackoverflow 上的帖子
Also please try to avoid naming variables as list
.另外请尽量避免将变量命名为list
。 It will get confusing later when you want to convert data to a list.稍后当您要将数据转换为列表时,它会变得混乱。
Example:例子:
x = {1:5,2:10,3:15}
y = list(x)
print (y)
will convert dictionary x
to a list y
将字典x
转换为列表y
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.