为了使用random.choice(),我必须将我的字符串转换为列表:
>>> x = "hello"
>>> y = list(x)
>>> y
['h', 'e', 'l', 'l', 'o']
Run Code Online (Sandbox Code Playgroud)
但试图反过来产生一个实际上看起来像['h', 'e', 'l', 'l', 'o']而不仅仅是的字符串hello.重复这样做会导致无限循环,产生如下所示的字符串:
"'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', "'", '"', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", '"', "'", ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' '
Run Code Online (Sandbox Code Playgroud)
等等.
那么,我怎样才能将列表转换回字符串:
>>> x = ['x', 'y', 'z']
>>> y = something(x)
>>> y
'xyz'
Run Code Online (Sandbox Code Playgroud)
>>> x = "hello"
>>> y = list(x)
>>> y
['h', 'e', 'l', 'l', 'o']
>>> ''.join(y)
'hello'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
329 次 |
| 最近记录: |