使用在Python中对齐的新行打印字符串 [英] Print string with new lines aligned in Python

查看:57
本文介绍了使用在Python中对齐的新行打印字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法来打印包含换行 \ n 且在一定数量的字符后向左对齐的字符串?

Is there an easy way to print a string that contains a new line \n, aligned to the left after a certain number of characters?

基本上,我拥有的是类似的东西

Basically, what I have is something like

A = '[A]: '
B = 'this is\na string\nwith a new line'

print('{:<10} {}'format(A, B))

问题在于,在新行中,下一行不会从第10列开始:

The problem is that with the new line, the next lines do not start at the 10th column:

[A]:       this is
a string
with a new line

我想要类似的东西

[A]:       this is
           a string
           with a new line

我可能会拆分 B ,但我想知道是否有一种可行的方法

I could maybe split B, but I was wondering if there was an optial way of doing this

推荐答案

一种简单的方法是用新行和11替换新行(由于 {:< 10}中的10,所以将其替换为11),但您在格式中添加了一个额外的空格)空格:

An easy way to achieve this is replacing a new line with a new line and 11 (11 because of the 10 in {:<10} but you add an additional space in your format) spaces:

B2 = B.replace('\n','\n           ')
print('{:<10} {}'.format(A, B2))

或更优雅:

B2 = B.replace('\n','\n'+11*' ')
print('{:<10} {}'.format(A, B2))

python3 中运行它:

$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> A = '[A]: '
>>> B = 'this is\na string\nwith a new line'
>>> B2 = B.replace('\n','\n           ')
>>> print('{:<10} {}'.format(A, B2))
[A]:       this is
           a string
           with a new line

这篇关于使用在Python中对齐的新行打印字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆