スキップしてメイン コンテンツに移動

Pythonでスペースを扱う


English ver


Introduction

コマンドラインで次のような表示をさせたい。
apple
  apple
    apple
      apple
        apple

失敗

次のようなprintを使ったcodeでは失敗する
def main():
    i = 0
    while i<5:
        print('apple')
        j = 0
        while j < i:
            print(' ')
            j = j + 1
        i = i + 1
if __name__ == '__main__':
    main()
結果は、、、
enter image description here
Printは使うごとに改行してしまうのです。

成功

次のようなcodeを見てください。
import sys

def main():
    i = 0
    while i < 5:
        print('apple')
        j = 0
        while j <= i:
            sys.stdout.write(' ')
            j = j + 1
        i  = i + 1
if __name__ == '__main__':
    main()
sys.stdout.write は改行を無視してくれます。
結果!!
enter image description here
一つ注意することはsys.stdout.weiteはstrしか受け付けないことです。

Reference

https://www.lifewithpython.com/2013/12/python-print-without-.html

コメント