Python Logic-使用句点将文本居中
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python Logic-使用句点将文本居中,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2077字,纯文字阅读大概需要3分钟。
内容图文
![Python Logic-使用句点将文本居中](/upload/InfoBanner/zyjiaocheng/678/3d0786b6f1184f4db693b7edd185def0.jpg)
我要this intro to python course online
问题显示为:
For this program, the first line of input is an integer width. Then, there are some lines of text; the line “END” indicates the end of the text. For each line of text, you need to print out a centered version of it, by adding periods .. to the left and right, so that the total length of each line of text is width. (All input lines will have length at most width.) Centering means that the number of periods added to the left and added to the right should be equal if possible; if needed we allow one more period on the left than the right. For example, for input
13
Text
in
the
middle!
END
正确的输出将是
.....Text....
......in.....
.....the.....
...middle!...
给出的提示是:
For input line length of L, you should add (width-L)\\2 periods to the right side
到目前为止,这是我的代码:
width = int(input())
s1 = input()
periods_remain = width - len(s1)
L = periods_remain
periods_rtside = (width-L)//2
periods_leftside = width - periods_rtside
periods_rt_str = '.' * periods_rtside
periods_left_str = '.' * periods_leftside
line1 = periods_left_str + s1 + periods_rt_str
我的line1结果看起来像是“ ……… Text ..”而不是… Text ….
我的问题似乎是L.我不确定如何定义L.谢谢!
解决方法:
您可以为此使用str.center:
>>> lis = ['Text', 'in', 'the', 'middle!', 'END']
>>> for item in lis:
... print item.center(13, '.')
...
.....Text....
......in.....
.....the.....
...middle!...
.....END.....
或格式:
for item in lis:
print format(item,'.^13')
...
....Text.....
.....in......
.....the.....
...middle!...
.....END.....
您的代码的工作版本:
lis = ['Text', 'in', 'the', 'middle!', 'END']
width = 13
for s1 in lis:
L = len(s1) #length of line
periods_rtside = (width - L)//2 #periods on the RHS
periods_leftside = width - periods_rtside - L #peroids on the LHS
periods_rt_str = '.' * periods_rtside
periods_left_str = '.' * periods_leftside
line1 = periods_left_str + s1 + periods_rt_str
print line1
输出:
.....Text....
......in.....
.....the.....
...middle!...
.....END.....
内容总结
以上是互联网集市为您收集整理的Python Logic-使用句点将文本居中全部内容,希望文章能够帮你解决Python Logic-使用句点将文本居中所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。