Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 208
sparx Avatar asked Nov 26 '25 18:11

sparx


2 Answers

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
like image 169
ncica Avatar answered Nov 29 '25 06:11

ncica


You can use join:

' '.join(bicycles)

', '.join(bicycles)
like image 21
Carsten Avatar answered Nov 29 '25 06:11

Carsten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!