简体   繁体   中英

How can I print list of items from multiple lines into a single line in Python?

I am trying to convert items list from multiple lines to a single line string and vice-versa. I am able to convert items from a single line string to multiple line vertical item list with following code:

Items = ["Apple","Ball","Cat"]
A = ("\n".join(Items))
print (A)  

Which prints item list as follows:

Apple  
Ball  
Cat   

I am all set with above code
My Question is regarding second code (which I can't figure out) down below:

However, I am unable to convert vertical list from multiple lines to a single line string.

I have following items in multiple lines;

 Apple  
 Ball  
 Cat

and I want to print them in a single line as:

 Apple Ball Cat  

I appreciate any kind of advice.

用这个替换你的代码:

A = (" ".join(Items))

You are joining the items with a new line character '\\n' . Try joining them with just a space ' ' .

So instead of

Items = ["Apple","Ball","Cat"]
A = ("\n".join(Items))
print (A)

You do

Items = ["Apple","Ball","Cat"]
A = (" ".join(Items))
print (A)

No join() required

things = ["Apple","Ball","Cat"]
s1 = ''

for item in things:
    s1 += item + ' '

print(s1.rstrip())

# output
''' Apple Ball Cat '''

print(A,end="") 用这个替换最后一行

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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