在字符串中的字符之间添加空格的有效方法
- 2025-04-10 09:45:00
- admin 原创
- 19
问题描述:
假设我有一个字符串s = 'BINGO'
;我想遍历该字符串来生成'B I N G O'
。
这是我做的:
result = ''
for ch in s:
result = result + ch + ' '
print(result[:-1]) # to rid of space after O
有没有更有效的方法来解决这个问题?
解决方案 1:
s = "BINGO"
print(" ".join(s))
應該做。
解决方案 2:
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
解决方案 3:
Python 方式
一种非常符合 Python 风格且实用的方法是使用字符串join()
方法:
str.join(iterable)
Python官方文档说:
返回一个字符串,该字符串是可迭代字符串的连接...元素之间的分隔符是提供此方法的字符串。
如何使用它?
记住:这是一个字符串方法。
此方法将应用于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'
解决方案 4:
最有效的方法是接受输入,制定逻辑并运行
所以代码就像这样,可以制作你自己的空间制造者
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))
解决方案 5:
def space_the_chars(string):
string = string.upper().replace(' ','')
return string.replace('',' ')[2:-2]
space_the_chars(“I’m going to be spaced”)
该函数将字符串的字符分隔开
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD