dor*_*mon 0 python newline carriage-return python-2.7
在python 2.7中如何实现以下功能:
print "some text here"+?+"and then it starts there"
Run Code Online (Sandbox Code Playgroud)
终端上的输出应如下所示:
some text here
and then it starts here
Run Code Online (Sandbox Code Playgroud)
我已经四处寻找,我认为\r应该做的工作,但我尝试了它不起作用.我现在很困惑.
顺便说一句,\r解决方案便携式?
PS在我奇怪的情况下,我认为了解prev行的长度对我来说非常困难.所以任何想法,而不是使用它上面的线的长度?
================================================== ================================
好的情况是这样的,我正在写一个树结构,我想用__str__函数很好地打印出来
class node:
def __init__(self,key,childern):
self.key = key
self.childern = childern
def __str__(self):
return "Node:"+self.key+"Children:"+str(self.childern)
Run Code Online (Sandbox Code Playgroud)
儿童是一个清单.
每次打印儿童时,我都希望它使用比最后一行更多的缩进.所以我想我无法预测我要打印的行之前的长度.
\r可能不是一个可移植的解决方案,它的呈现方式取决于你正在使用的任何文本编辑器或终端.在较旧的Mac系统上,'\r'被用作行尾字符(在Windows上它是'\r\n'在Linux和OSX上)'\n'.
你可以简单地做这样的事情:
def print_lines_at_same_position(*lines):
prev_len = 0
for line in lines:
print " "*prev_len + line
prev_len += len(line)
Run Code Online (Sandbox Code Playgroud)
用法示例:
>>> print_lines_at_same_position("hello", "world", "this is a test")
hello
world
this is a test
>>>
Run Code Online (Sandbox Code Playgroud)
这只有在您输出的内容具有固定字符长度的字体时才有效.我想不出任何可行的方法
编辑以适应更改的问题
好的,这是一个完全不同的问题.我不认为有任何的方式使用它开始做究竟在那里的最后一行离开,除非该位置self.key具有可预测的长度.但你可以得到一些非常接近的东西:
class node:
def __init__(self,key,children):
self.key = key
self.children = children
self.depth = 0
def set_depth(self, depth):
self.depth = depth
for child in self.children:
child.set_depth(depth+1)
def __str__(self):
indent = " "*4*self.depth
children_str = "\n".join(map(str, self.children))
if children_str:
children_str = "\n" + children_str
return indent + "Node: %s%s" % (self.key, children_str)
Run Code Online (Sandbox Code Playgroud)
然后只需将根节点的深度设置为0,并在每次更改树的结构时再次执行此操作.如果你确切知道如何更改树,有更有效的方法,你可以自己解决这些问题:)
用法示例:
>>> a = node("leaf", [])
>>> b = node("another leaf", [])
>>> c = node("internal", [a,b])
>>> d = node("root", [c])
>>> d.set_depth(0)
>>> print d
Node: root
Node: internal
Node: leaf
Node: another leaf
>>>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
157 次 |
| 最近记录: |