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

投稿

ラベル(Python(日本語))が付いた投稿を表示しています

Pythonでスペースを扱う

English ver Introduction 失敗 成功 Reference 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() 結果は、、、 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 は改行を無視してくれます。 結果!! 一つ注意することはsys.stdout.weiteはstrしか受け付けないことです。 Reference https://www.lifewithpython.com/2013/12/python-print-without-.html