从零开始学Python

Python习题册001:格式化输出

2019-01-13  本文已影响0人  iLester

任务001描述:

编写一个Python程序,以特定的格式输出。示例字符串及输出效果如下:
示例字符串: "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are" Output :
输出效果:

Twinkle, twinkle, little star,
    How I wonder what you are! 
        Up above the world so high,         
        Like a diamond in the sky. 
Twinkle, twinkle, little star, 
    How I wonder what you are

思路及解决方案

主要考察print()函数中的置换符,观察输出信息,有换行,有缩进。可以用\n换行,\t缩进一个制表位。
参考代码如下:

print("Twinkle, twinkle, little star, \n\tHow I wonder what you are! \n\t\tUp above the world so high, \n\t\tLike a diamond in the sky. \nTwinkle, twinkle, little star, \n\tHow I wonder what you are!")

输出效果如下:

Twinkle, twinkle, little star,
    How I wonder what you are! 
        Up above the world so high,         
        Like a diamond in the sky. 
Twinkle, twinkle, little star, 
    How I wonder what you are!

注:翻译自w3resource网站的Python Basic Part 1(初学者练习题)。

上一篇 下一篇

猜你喜欢

热点阅读