python - 给定需要添加的空格数量,通过在单词之间添加空格来格式化字符串
问题描述
给定一个起始字符串,并且需要在字符串中添加多个空格,有没有一种简单的方法可以做到这一点?如果空格数分布不均匀,请从左到右添加空格。
这是我尝试过的:
将空格数除以实际的字符串空格
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 数量的空格字符。关于如何添加最后一个空格或找到更好的方法的任何提示?
这是一个例子:
“阿尔杰农。你听到我在演奏什么了吗,莱恩?”
并且给定 space_Count = 12,应该给
Algernon. Did you hear what I was playing, Lane?
编辑:让它工作!
解决方案
我认为您在这里走在正确的轨道上,但是您似乎在替换最右边的实例而不是最左边的实例时遇到了麻烦。要从右侧而不是从左侧开始替换,您可以反转您的字符串,然后执行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?'
当然,将其余空格从左侧而不是从右侧放入将返回您在问题中提到的字符串。这种修改应该是直截了当的。
推荐阅读
- c++ - 为什么班级专业化会出现错误?
- ruby-on-rails - 如何设置 ActionMailer 使用 TLS 连接所需的 SSL 协议?
- javascript - Express req.ip 在看似随机的基础上在报告我的本地计算机地址为 ::ffff:127.0.0.1 和 ::1 之间切换
- excel - 在 VBA 中访问 IFRAME
- javascript - 使用 tooltip.style("opacity","0") vs tooltip.style.opacity = 0 改变不透明度
- r - R 3.5.2 版本:找不到 Rmysql 或 pool 或 devtools 包
- python - 如何将字典格式的txt文件转换为python中的数据框?
- reactjs - React Native 的文档?我可以使用普通的 React 文档吗?
- python - 如何使用 python CTRL+V 进入 Excel
- mysql - 数据库级别的 MySQL 分片