dumb_guy
dumb_guy

Reputation: 101

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.

Upvotes: 1

Views: 1967

Answers (5)

Moamar
Moamar

Reputation: 1

skills = ["HTML", "CSS", "JavaScript", "PHP", "Python"] while skills:print("\n".join(skills)); break

Upvotes: -1

Ashish Thapa
Ashish Thapa

Reputation: 16

print(A,end="") replace the last line with this

Upvotes: 0

Michael Swartz
Michael Swartz

Reputation: 858

No join() required

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

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

print(s1.rstrip())

# output
''' Apple Ball Cat '''

Upvotes: 0

Ethan Smith
Ethan Smith

Reputation: 21

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)

Upvotes: 2

Alberto
Alberto

Reputation: 31

Replace your code with this:

A = (" ".join(Items))

Upvotes: 3

Related Questions