0

Python 2.7では、次の機能をどのように実現できますか:

print "some text here"+?+"and then it starts there"

端末の出力は次のようになります。

some text here
              and then it starts here

私は周りを検索しましたが、仕事をするべきだと思います\rが、試してみましたがうまくいきません。私は今混乱しています。

ところで、\rソリューションは移植可能ですか?

PS私の奇妙な状況では、前の行の長さを知ることは私にとって非常に難しいと思います. その上の線の長さを使用するのではなく、何か考えはありますか?

================================================== ================================

さて、状況はこのようなものです。私はツリー構造を書いていて、__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)

Children はリストです。

Children を印刷するたびに、最後の行よりも 1 つ多くインデントしてください。そのため、印刷したい行の前の長さを予測できないと思います。

4

4 に答える 4

5

\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)

使用例:

>>> print_lines_at_same_position("hello", "world", "this is a test")
hello
     world
          this is a test
>>> 

ただし、これは、出力先に固定文字長のフォントがある場合にのみ機能します。それ以外にうまくいくものは考えられない

変更された質問に合わせて編集

さて、それはまったく別の質問です。予測可能な長さでない限り、最後の行が中断した正確な位置から開始する方法はないと思います。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)

次に、ルート ノードの深さを 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
>>> 
于 2013-02-25T21:29:12.490 に答える
0

Windowsの\r改行の一部であるため、解決策はあなたが探しているものではありませんが、Macシステムでは実際には改行です。

次のようなコードが必要です。

def pretty_print(text):
    total = 0
    for element in text:
        print "{}{}".format(' '*total, element)
        total += len(element)

pretty_print(["lol", "apples", "are", "fun"])

これにより、テキスト行が希望どおりに印刷されます。

于 2013-02-25T21:33:09.150 に答える
0

os.linesepの代わりに、より移植性の高い改行を取得するために使用できます\r。次に、len()空白を計算するために、最初の文字列の長さを計算するために使用します。

>>> import os
>>> my_str = "some text here"
>>> print my_str + os.linesep + ' ' * len(my_str) + 'and then it starts here'
some text here
              and then it starts here

キーは' ' * len(my_str)です。これにより、スペース文字が繰り返されlen(my_str)ます。

于 2013-02-25T21:31:19.313 に答える
0

len("text") * ' ' を使用して、必要な空白の量を取得してみてください。

移植可能な改行を取得するには、os.linesep を使用します。

>>> import os
>>> os.linesep
'\n'

編集

場合によっては適切な別のオプションは、stdout ストリームをオーバーライドすることです。

import sys, os

class StreamWrap(object):

        TAG = '<br>' # use a string that suits your use case

        def __init__(self, stream):
                self.stream = stream

        def write(self, text):
                tokens = text.split(StreamWrap.TAG)
                indent = 0
                for i, token in enumerate(tokens):
                        self.stream.write(indent*' ' + token)
                        if i < len(tokens)-1:
                                self.stream.write(os.linesep)
                        indent += len(token)

        def flush(self):
                self.stream.flush()

sys.stdout = StreamWrap(sys.stdout)

print "some text here"+ StreamWrap.TAG +"and then it starts there"

これにより、次のような結果が得られます。

>>> python test.py 
some text here
          and then it starts there
于 2013-02-25T21:26:20.200 に答える