我有一个列表,其中包含一些书籍名称及其作者,但我希望它看起来很有条理,所以我希望它能够获得书名,然后用空格填写它,最终得到100个字符,与书的长度无关标题.然后,它会添加书名.
到目前为止,我试过这个:
for i in range(0, len(bookList)):
t = 100 - len(bookList[i])
numbofspaces = ""
for j in range(0, t):
numbofspaces += " "
s.append(bookList[i] + numbofspaces + authorList[i])
Run Code Online (Sandbox Code Playgroud)
当我在python shell中尝试它时它工作得很好,但是当它从列表中获取标题时,它不起作用,为什么呢?
使用字符串方法: str.rjust(100)
>>> x = [ 'charles dickens','shakespeare','j k rowling']
>>> for name in x:
... print(name.rjust(50))
...
charles dickens
shakespeare
j k rowling
Run Code Online (Sandbox Code Playgroud)
虽然str.ljust()/ str.rjust()好,简单的解决方案,如果这是你想做的事,这是值得注意的是,如果你正在做其他格式,你可以做到这一点作为字符串格式化的一部分:
>>> '{:<30}'.format('left aligned')
'left aligned '
>>> '{:>30}'.format('right aligned')
' right aligned'
Run Code Online (Sandbox Code Playgroud)
来自文档.