说我有一个字符串s = 'BINGO'; 我想迭代字符串来生成'B I N G O'.
这就是我做的:
result = ''
for ch in s:
result = result + ch + ' '
print(result[:-1]) # to rid of space after O
Run Code Online (Sandbox Code Playgroud)
有没有更有效的方法来解决这个问题?
Kev*_*don 41
s = "BINGO"
print(" ".join(s))
Run Code Online (Sandbox Code Playgroud)
应该这样做.
Joh*_*ooy 20
s = "BINGO"
print(s.replace("", " ")[1: -1])
Run Code Online (Sandbox Code Playgroud)
时间如下
$ python -m timeit -s's = "BINGO"' 's.replace(""," ")[1:-1]'
1000000 loops, best of 3: 0.584 usec per loop
$ python -m timeit -s's = "BINGO"' '" ".join(s)'
100000 loops, best of 3: 1.54 usec per loop
Run Code Online (Sandbox Code Playgroud)