给出一个起始字符串,并且需要在字符串中添加许多空格,是否有一种简单的方法?如果空格数分布不均匀,请从右到左添加空格。
这是我尝试过的:
将空格号与实际字符串空格相除
div = spaces // (word_count - 1)
标记字符串
temp = st.split()
for i in range(len(temp)):
如果第一个单词只是添加当前单词而没有空格
if i == 0:
st = temp[0]
如果第一个单词只是添加当前单词而没有空格
else:
将div的空格数量+原始空格添加到单词中
st = st + " "*div + " " +temp[i]
更新我们的空间计数
space_count = space_count - div
space_count匹配或小于字符串中的实际空格量
if space_count <= word_count -1:
st = st.replace(" ", " ", space_count)
添加一个额外的空间,即“ space_count”次。这就是问题所在,它仅替换第一个space_count个空格字符。关于如何添加最后一个空格或找到更好的方法的任何提示?
这里是一个例子:
“ Algernon。你听到我在玩什么吗,Lane?”
并给定space_Count = 12,应给出
Algernon. Did you hear what I was playing, Lane?
编辑:成功了!
答案 0 :(得分:3)
我认为您在这里的方向正确,但是似乎在替换最右边的实例而不是最左边的实例时遇到了麻烦。要从右开始而不是从左开始替换,可以反转字符串,然后执行replace
操作,然后再次反转。在以下代码段中,我通过字符串切片来完成此操作:sentence[::-1]
。
因此,以下代码段首先计算了原始短语(要替换)(num_spaces
)中的空格数,然后计算了每个空格中需要添加的空格数的下限。原始(div
),然后需要从右侧添加{num_extra
)的多余空格数。然后,它反转字符串并将num_extra
空格替换为' ' + ' ' * div
;那是原始空间,再加上div
个空间,再加上一个额外的空间。然后再次将字符串反转,剩下的空格仅用' ' + ' ' * div
代替-相同,但没有剩余空格。
def add_spaces(sentence, ct):
num_spaces = sentence.count(' ') # find number of spaces in the original phrase
div = (ct // num_spaces) # find base of number of spaces to add
num_extra = ct % num_spaces # find the number of left-over spaces
# now use string replacements to re-add the spaces.
# first, change the rightmost num_extra occurrences to have more spaces,
# by reversing the string, doing the replace, and then un-reversing it.
# this is somewhat of a hacky work-around for replacing starting from right
new_sentence = sentence[::-1].replace(' ', ' ' + ' ' * div, num_extra)[::-1]
# then, simply replace the rest of the spaces properly
new_sentence = new_sentence.replace(' ', ' ' + ' ' * div, num_spaces - num_extra)
return new_sentence
当我在控制台中尝试时,此代码片段会弹出:
>>> add_spaces("Algernon. Did you hear what I was playing, Lane?", 12)
'Algernon. Did you hear what I was playing, Lane?'
当然,将其余空格从左侧而不是从右侧放入将返回您在问题中提到的字符串。修改应该很简单。
答案 1 :(得分:0)
以另一种方式解决此问题:
import re
def addspaces(txt, nspaces):
gaps = list(re.finditer(r'\s+', txt))
(base, rem) = divmod(nspaces, len(gaps))
base = ' ' * base
# generate a list of spaces to add
toadd = (
[base] * (len(gaps) - rem) +
[base + ' '] * rem
)
out = []
i = 0
for m, sp in zip(gaps, toadd):
out.extend((txt[i:m.end(0)], sp))
i = m.end(0)
out.append(txt[i:])
return ''.join(out)
addspaces("Algernon. Did you hear what I was playing, Lane?", 12)
给予
'Algernon. Did you hear what I was playing, Lane?'
这会在右侧保留多余的空间(如您所愿),但您可以在初始化toadd
时交换内容