0

In order to use random.choice(), I have to convert my string to a list:

>>> x = "hello"
>>> y = list(x)
>>> y
['h', 'e', 'l', 'l', 'o']

But trying to do that in reverse yields a string that actually looks like ['h', 'e', 'l', 'l', 'o'] instead of just hello. Doing this repeatedly causes an infinite loop that produces strings which look like this:

"'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', "'", '"', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", '"', "'", ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' '

And so on.

So, how can I convert the list back into a string:

>>> x = ['x', 'y', 'z']
>>> y = something(x)
>>> y
'xyz'
zhangyangyu
  • 8,262
  • 2
  • 32
  • 43
tkbx
  • 14,366
  • 27
  • 82
  • 118

7 Answers7

7

"".join (x) will do it quite easily.

Owen
  • 1,694
  • 10
  • 15
5
>>> x = "hello"
>>> y = list(x)
>>> y
['h', 'e', 'l', 'l', 'o']
>>> ''.join(y)
'hello'
devnull
  • 111,086
  • 29
  • 224
  • 214
4

To convert a list to a string in python like you want, you can use the string.join operator.

 >>> x = ['x', 'y', 'z']
 >>> y = "".join(x)
 >>> y
 'xyz'
Matt Bryant
  • 4,741
  • 4
  • 30
  • 46
4

Python String join does the trick.

>>> ''.join(y)
'xyz'
Srikar Appalaraju
  • 69,116
  • 53
  • 210
  • 260
4
>>> x = 'abc'
>>> y = list(x)
>>> y
['a', 'b', 'c']
>>> ''.join(y)
'abc'
>>> 

And to use random.choice, there is no need for you to parse the string to list, the string itself is a sequence:

>>> random.choice('abc')
'c'
>>> random.choice('abc')
'a'
>>> 
zhangyangyu
  • 8,262
  • 2
  • 32
  • 43
3

While several of these answers correctly answer the question of converting a list to a string, I would note that your actual problem is that you want to use random.choice() on a string and want to convert it to a list first. You don't need to do that -- random.choice() takes any sequence, including a string.

x = 'abcde'
y = [random.choice(x) for i in range(5)]
print y
llb
  • 1,581
  • 9
  • 14
  • That would be easier, but I need `list`'s `insert`, `remove`, `index`, etc, and string --> list --> string winds up being worth the extra step in this case. – tkbx Jul 10 '13 at 04:27
2

Use join:

>>> li=['h', 'e', 'l', 'l', 'o']
>>> print ''.join(li)

ie, that reverses what applying the list constructor does to a string:

>>> ''.join(list('hello'))
'hello'
dawg
  • 90,796
  • 20
  • 120
  • 197
  • May I ask why the down vote? – dawg Jul 10 '13 at 04:26
  • I didn't do the downvote, but I notice that @MattBryant also has a downvote and your two posts are the only two that define the list directly instead of generating them from a string... Maybe somebody *really* doesn't like creating lists of characters directly? – SethMMorton Jul 10 '13 at 06:19