[Tutor] Noob question

Eric Walstad eric at ericwalstad.com
Sun Dec 9 22:40:27 CET 2007


Eric Brunson wrote:
> quantrum75 wrote:
>> Hi there,
>> I am a newbie trying to actively learn python.
>> My question is,
>> Suppose I have a list
>> a=["apple","orange","banana"]
>>
>> How do I convert this list into a string which is
>>
>> b="appleorangebanana"
>> Sorry for my ignorance, 
> 
> No worries, every new language has its idioms that only come from 
> experience and exposure.
> 
> Try this:
> 
> In [1]: a=["apple","orange","banana"]
> 
> In [2]: print "".join( a )
> appleorangebanana
> 
> And just for clarity:
> 
> In [3]: print "|".join( a )
> apple|orange|banana

And another good reference for you to know about is the built-in help
system that comes with Python.  For example, to learn a bit about why
Eric's code works the way it does:
>>> help("".join)

Help on built-in function join:

join(...)
    S.join(sequence) -> string

    Return a string which is the concatenation of the strings in the
    sequence.  The separator between elements is S.


In Eric's example, the variable 'a' was a type of Python sequence,
specifically, a list.


You could also achieve the same result of concatenating a list of
strings by looping over the list items like so:

b = ''
for fruit in a:
    b += fruit

print b

Eric.


More information about the Tutor mailing list