概述
我正在编写一个函数,它应该接受一个整数w和一个字符串text,并返回一个字符串
1)线路长度为w(最后一条线路可根据需要缩短)
2)如果一个单词大于一行,则该单词将被换行到下一行
3)如果有连续的空格,我们将不输出额外的空格
示例
如果语法正确,我的函数也能正常工作,但是我必须考虑第二个例子。在
例1>>> w = 17
>>> text = "Hi my name is bob I like to go to the park"
>>> bend(w, text)
Hi my name is bob
I like to go to
the park
例2
^{pr2}$
多个连续的打印都失败了a
b
c
何时应该打印a
b
c
“但是,它将在空格处而不是文本中的单词中心处断开长线“
例3
卡在这部分。有没有更简单的方法可以知道一个单词是否可以用给定的整数w拼写出来?在w = 4
text = "ab bob"
bend(w,text)应该打印ab
bob
而不是abbo
ob
这是我目前为止的代码def bend(w, text):
'''(int, str) -> NoneType
Takes an integer w as the character length of each line.
However, it will break long lines at a space rather than
center of a word in text.
a = ""
i = 0
line_count = 0
occur = True
while (i < len(text)):
if(text[i] == " "):
word_full = True
j = i + 1
no_space = True
line_test = line_count + 1
while (j < len(text) and no_space == True):
if(text[j] == " " or (j+1) == len(text)):
word_full = False
no_space = False
elif (line_test % w == 0):
no_space = False
else:
j = j + 1
line_test += 1
if(word_full == True):
print(a)
a = ""
a += text[i+1]
line_count = 0
i = i + 2
else:
if(line_count != 0):
a += text[i]
i = i + 1
else:
a += text[i+1]
i = i + 2
line_count += 1
elif((line_count+1) % w == 0 and line_count != 0):
a += text[i]
print(a)
a = ""
i = i + 1
line_count = 0
else:
a += text[i]
i = i + 1
line_count += 1
print(a)
text = "Hi my name is bob I like to go to the park"
w = 17
bend(w, text)
最后
以上就是标致万宝路为你收集整理的python字符串相加算法_python算法迭代一个字符串,但在给定的整数后加一个新行...的全部内容,希望文章能够帮你解决python字符串相加算法_python算法迭代一个字符串,但在给定的整数后加一个新行...所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复