Python 在字符串中的字符之间添加空格。最有效的方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18221436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:14:40 来源:igfitidea点击:
Python adding space between characters in string. Most efficient way
提问by user2425814
Say I have a string s = 'BINGO'
; I want to iterate over the string to produce 'B I N G O'
.
假设我有一个字符串s = 'BINGO'
;我想遍历字符串以产生'B I N G O'
.
This is what I did:
这就是我所做的:
result = ''
for ch in s:
result = result + ch + ' '
print(result[:-1]) # to rid of space after O
Is there a more efficient way to go about this?
有没有更有效的方法来解决这个问题?
回答by Kevin London
s = "BINGO"
print(" ".join(s))
Should do it.
应该做。
回答by John La Rooy
s = "BINGO"
print(s.replace("", " ")[1: -1])
Timings below
下面的时间
$ 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