[Tutor] convert array into string
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Fri, 30 Aug 2002 08:35:37 -0700 (PDT)
On Fri, 30 Aug 2002, Kyle Babich wrote:
> How would I convert something like:
> abc = ["abcdef"]
> into
> abc = "abcdef"
>
> What I'm actually trying to do is convert a file.readlines() into a
> single string and then .split(" "). Is this possible?
Yes --- it sounds like you'd like to join all the strings in your list
together. The string.join() function is especially good for this:
###
>>> sentence = ["there", "is", "no", "spoon"]
>>> string.join(sentence, " ")
'there is no spoon'
###
In Python 2, the joining functionality was migrated directly into the
string class itself --- join() is now a method that all strings have:
###
>>> ' '.join(sentence)
'there is no spoon'
>>> '+'.join(sentence)
'there+is+no+spoon'
###
But if the source of your data is a file, there's a way of pulling the
whole file into a string, without going through this intermediate string
join step:
###
story_file = open("mystory.txt")
contents = story_file.read()
###
The read() method will, by default, suck everything out of a file, and is
probably a better way of approaching this problem than the
readlines()/join().
Good luck!