简体   繁体   English

当我打印 Python 列表时,如何做到这一点,当我打印列表时,每个项目都没有单引号和括号?

[英]How do I make it so when I print a Python list it doesn't have the single quotes and brackets with each item when I print the list?

Ok so I have been coding Python and when I run this code好的,所以我一直在编码 Python 并且当我运行此代码时

names = ["Harry", " Ron", "Hermione"]
print(names)
# output: ['Harry', ' Ron', 'Hermione']

How do I make it so it doesn't have the [] and the ' '.我如何使它没有[]和''。 Thanks!谢谢!

Depending upon you want the output to be, you can use根据您希望 output 成为,您可以使用

print(*names,sep=' ')

by default sep value is ' '.默认 sep 值为 ' '。 If you want to print all elements in new line then pass '\n' as sep.如果要在新行中打印所有元素,则将 '\n' 作为 sep 传递。

print(", ".join(names))

Two ways come to mind if you want to maintain the comma separator:如果要维护逗号分隔符,可以想到两种方法:

print(*names,sep=",")

or或者

print(','.join(names))

This should do it这应该这样做

names = ["Harry", " Ron", "Hermione"]

for name in names:
    print(name, end=" ")
print(', '.join([n.strip() for n in names]))

or (tks to @Ryan Haining)或(感谢@Ryan Haining)

print(*[n.strip() for n in names]) 

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

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