2018年1月8日 星期一

Python: Print a string in a specified format


Python: Print a string in a specified format

Python Basic: Exercise-1 with Solution

Write a Python program to print the following string in a specific format (see the output).
Sample String: "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!"
The print statement (Python 2.6) has been replaced with a print() function (Python 2.6), with keyword arguments to replace most of the special syntax of the old print statement .
  • The print() function doesn’t support the “softspace” feature of the old print statement. For example, in Python 2.x, print "A\n", "B" would write "A\nB\n"; but in Python 3.0, print("A\n", "B") writes "A\n B\n".
  • Initially, you’ll be finding yourself typing the old print x a lot in interactive mode. Time to retrain your fingers to type print(x) instead!
  • When using the 2to3 source-to-source conversion tool, all print statements are automatically converted to print() function calls, so this is mostly a non-issue for larger projects.
Examples:
Old: print "The answer is", 3*3
New: print("The answer is", 3*23

Old: print a,           # Trailing comma suppresses newline
New: print(a, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (a, b)       # prints repr((a, b))
New: print((a, b))      # Not the same as print(a, b)
Sample Solution:-


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!")


================== RESTART: F:/Python_APSC/py-ex-basic-1.py ==================
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!
>>> 

沒有留言:

張貼留言

WOKWI LED + MQTT Node-Red SQLite

WOKWI LED + MQTT Node-Red SQLite const char *mqtt_broker = "broker.mqtt-dashboard.com" ; const char *topic1 = "alex9ufo/e...