Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Unpack lists and join into a string

Tags:

python

perl

I am new to Python, but I have experience in Perl coding.

I wonder if there is an elegant way to 'join' lists into a string like following Perl example in Python.

my $brands = [ qw( google apple intel qualcomm ) ]; #1st List  
my $otherBrands = [ qw( nike reebok puma ) ]; #2nd List  

say join ':' , ( @{$brands} , @{$otherBrands} );  
# print "google:apple:intel:qualcomm:nike:reebok:puma"

I've searched this for a while, but most of the answer are using * for unpacking which is not feasible in my case.

like image 516
PeterHsu Avatar asked May 19 '15 02:05

PeterHsu


2 Answers

You can use + to join two lists, and join to join them.

brands = ["google", "apple", "intel", "qualcomm"]
otherBrands = ["nike", "reebok", "puma"]

print ":".join(brands + otherBrands)

If you are looking for syntax similar to qw in Perl (to create a list of string literals without quotes), that does not exist in Python as far as I know.

like image 189
merlin2011 Avatar answered Sep 19 '22 16:09

merlin2011


You can try the following

list1 = ['google', 'apple', 'intel', 'qualcomm']
list2 = ['nike', 'reebok', 'puma']
your_string = ":".join(list1+list2)

The output should be

'google:apple:intel:qualcomm:nike:reebok:puma'
like image 25
Paul Rigor Avatar answered Sep 19 '22 16:09

Paul Rigor