w3resource

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.

Pictorial Presentation:

Print a string in a specified format

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:

Python Code:

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

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!
 

Flowchart:

Flowchart: Print a string in a specified format.

Python Code Editor:


Previous: Python Basic Exercises Home.
Next: Write a Python program to get the Python version you are using.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.