2024-05-13 00:10:10 发布
网友
假设我有一个字符串s = 'BINGO';我想遍历该字符串以生成'B I N G O'。
s = 'BINGO'
'B I N G O'
我就是这么做的:
result = '' for ch in s: result = result + ch + ' ' print(result[:-1]) # to rid of space after O
有没有更有效的方法来解决这个问题?
s = "BINGO" print(" ".join(s))
应该这么做。
s = "BINGO" print(s.replace("", " ")[1: -1])
以下计时
$ 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
应该这么做。
以下计时
相关问题 更多 >
编程相关推荐