Help for Python newbie

Greg Jorgensen gregj at pobox.com
Tue Jun 12 11:30:09 CEST 2001


You can use the join function from the string module like this:

>>> import string
>>> mylist = ['1', '2', '3']
>>> mystring = string.join(mylist, '\t')
>>> mystring
'1\t2\t3'

Or you can use the string type's join method. The trick is to remember that
join is a method of the string, not of the list:

>>> mystring = '\t'.join(mylist)
>>> mystring
'1\t2\t3'

This may be clearer:

>>> delim = '\t'
>>> mystring = delim.join(mylist)

Greg Jorgensen
PDXperts LLC
Portland, Oregon, USA
gregj at pdxperts.com


----- Original Message -----
From: "Bob Hibberdine" <bob.hibberdine at ntlworld.com>
Newsgroups: comp.lang.python
Sent: Tuesday, June 12, 2001 2:01 AM
Subject: Help for Python newbie


> Hi,
>
> Any help with the following much appreciated.
>
> I want to convert a list of items into a tab separated string. According
the
> Python manuals I can use join:
>
> I quote from the manual:
>
> join (words[, sep])
>     Concatenate a list or tuple of words with intervening occurrences of
> sep. The default value of sep is a single space character......
>
> here's the output from the interpreter:
>
> PythonWin 2.0 (#8, Mar  7 2001, 16:04:37) [MSC 32 bit (Intel)] on win32.
> Portions Copyright 1994-2001 Mark Hammond (MarkH at ActiveState.com) - see
> 'Help/About PythonWin' for further copyright information.
> >>>
> >>> import string
> >>> mylist = ['1','2','3']
> >>> mystring = ''
> >>> mystring = mystring.join(mylist)
> >>> print mystring
> 123
>
> note there is no space between the items.
>
> Now, I try to use join as I want, I get:
>
> >>> mystring = mystring.join(mylist,'\t')
> Traceback (innermost last):
>   File "<interactive input>", line 1, in ?
> TypeError: join requires exactly 1 argument; 2 given
> >>>
>
> I got my python  form ActiveState and am working on Win98.
>
> Thanks in advance.
> Bob Hibberdine






More information about the Python-list mailing list