Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine array into one string [duplicate]

Tags:

python

I want to be able to combine a variable length array into a single string, for example:

var1 = ['Hello',' ','World','!']

becomes:

var2 = 'Hello World!'

and the first array may be bigger than 4. Thanks for any help!

like image 286
ZachHofmeister Avatar asked Apr 17 '26 18:04

ZachHofmeister


1 Answers

str.join()

Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string providing this method.

List items will be joined (concatenated) with the supplied string. Using '' will join all items with no character between them.

Python 3.5.1 (v3.5.1:37a07cee5969, Dec  5 2015, 21:12:44) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> var1 = ['hello', ' ', 'world', '!']
>>> ''.join(var1)
'hello world!'
>>> '     '.join(var1)
'hello           world     !'
>>> '*%*%*'.join(var1)
'hello*%*%* *%*%*world*%*%*!'
>>> 
like image 67
spectre-d Avatar answered Apr 19 '26 09:04

spectre-d



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!