sparx
sparx

Reputation: 51

Python 3.5: Is there a way to make this list more organized?

Say you have the following code:

bicycles = ['Trek','Cannondale','Redline','Secialized']
print(bicycles[0],bicycles[1],bicycles[2],bicycles[3])

This would print out:

Trek Cannondale Redline Specialized

I have two questions. First, Is there a way to make the print string more organized so that you don't have to type out bicycles multiple times? I know that if you were to just do:

print(bicycles)

It would print the brackets also, which I'm trying to avoid.

Second question, how would I insert commas to display within the list when its printed?

This is how I would like the outcome:

Trek, Cannondale, Redline, Specialized.

I know that I could just do

print("Trek, Cannondale, Redline, Specialized.")

But using a list, is there anyway to make it more organzed? Or would printing the sentence out be the smartest way of doing it?

Upvotes: 2

Views: 184

Answers (2)

ncica
ncica

Reputation: 7206

use .join() method:

The method join() returns a string in which the string elements of sequence have been joined by str separator.

syntax: str.join(sequence)

bicycles = ['Trek','Cannondale','Redline','Secialized']
print (' '.join(bicycles))

output:

Trek Cannondale Redline Secialized

Example: change separotor into ', ':

print (', '.join(bicycles))

output:

Trek, Cannondale, Redline, Secialized

For python 3. you can also use unpacking:

We can use * to unpack the list so that all elements of it can be passed as different parameters.

We use operator *

bicycles = ['Trek','Cannondale','Redline','Secialized']
print (*bicycles)

output:

Trek Cannondale Redline Secialized

NOTE: It's using ' ' as a default separator, or specify one, eg:

print(*bicycles, sep=', ')

Output:

Trek, Cannondale, Redline, Secialized

It will also work if the elements in the list are different types (without having to explicitly cast to string)

eg, if bicycles was ['test', 1, 'two', 3.5, 'something else']

bicycles = ['test', 1, 'two', 3.5, 'something else']
print(*bicycles, sep=', ')

output:

test, 1, two, 3.5, something else

Upvotes: 7

Carsten
Carsten

Reputation: 3048

You can use join:

' '.join(bicycles)

', '.join(bicycles)

Upvotes: 1

Related Questions