Python在字符串中的字符之间添加空格。最有效的方式

时间:2013-08-14 00:36:20

标签: python string

说我有一个字符串s = 'BINGO';我想迭代字符串以生成'B I N G O'

这就是我所做的:

result = ''
for ch in s:
   result = result + ch + ' '
print(result[:-1])    # to rid of space after O

有没有更有效的方法来解决这个问题?

4 个答案:

答案 0 :(得分:39)

s = "BINGO"
print(" ".join(s))

应该这样做。

答案 1 :(得分:20)

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

答案 2 :(得分:1)

一种非常Python实用的方法是使用字符串join()方法:

str.join(iterable)

官方Python documentations说:

返回一个字符串,该字符串是可迭代的字符串的串联...元素之间的分隔符是提供此方法的字符串。

如何使用它?

记住:这是一个字符串方法

此方法将应用于上面的str,该方法将反映将用作迭代器中项目分隔符的字符串。

让我们举一些实际的例子!

iterable = "BINGO"
separator = " " # A whitespace character.
                # The string to which the method will be applied
separator.join(iterable)
> 'B I N G O'

在实践中,您可以这样做:

iterable = "BINGO"    
" ".join(iterable)
> 'B I N G O'

但是请记住,该参数是可迭代的,例如字符串,列表,元组。尽管该方法返回了一个字符串。

iterable = ['B', 'I', 'N', 'G', 'O']    
" ".join(iterable)
> 'B I N G O'

如果使用连字符代替字符串会发生什么情况?

iterable = ['B', 'I', 'N', 'G', 'O']    
"-".join(iterable)
> 'B-I-N-G-O'

答案 3 :(得分:-1)

最有效的方法是获取输入生成逻辑并运行

所以代码是这样制作自己的space maker

need = input("Write a string:- ")
result = ''
for character in need:
   result = result + character + ' '
print(result)    # to rid of space after O

但是如果你想使用python提供的东西,那么使用这个代码

need2 = input("Write a string:- ")

print(" ".join(need2))
相关问题