9. More on print()
9.1 Special characters
\n
indicates a line break. Any text after this character will be printed on a new line.\t
indicates a tab or indent. Any text after this character will be indented.\
is an escape character and signals python that the text immediately after is a part of the string
Example:
1print('Hello \n\tworld. It\'s \n\n \t\ttime to wake \nup')
1Hello2 world. It's34 time to wake5up
9.2 Concatenation
Pass several arguments separated by commas. A space will be added between each argument.
1h = 'Hello'2w = 'world'3print(h,w)
1Hello world
9.3 f-strings
Declaring a string: Preface a string with the letter f and place variable names inside curly brackets.
Example:
1item = 'PlayStation';2price = 500;3available = 'is not'45feedback = f'The item {item} cost ${price} and {available} available.'6print(feedback)
1The item PlayStation cost $500 and is not available.
Formatting numbers: use :.nf
after a variable where n
is the number of decimal places to display. Similarly, use :.n%
to format percentages.
1feedback = f'The item {item} cost ${price:.2f} and {available} available.'2print(feedback)
1The item PlayStation cost $500.00 and is not available.
Formatting strings:
Use :<n
to format strings. <
says left aligned and n
fixes the number of spaces to print. Use >
to right align.
1feedback = f'The item {item:<20} cost ${price:.2f} and {available} available.'2print(feedback)3feedback = f'The item {item:>20} cost ${price:.2f} and {available} available.'4print(feedback)
1The item PlayStation cost $500.00 and is not available.2The item PlayStation cost $500.00 and is not available.
9.4 end=
argument
Specify what to print at the end of each call to print()
. By default, end = '\n'
causing each call to print to end with a new line.
Example: US phones numbers consist of a 3-digit area code, a 3-digit central office code, and a 4-digit subscriber code, and are usually formatted like 123-456-7890. Obtain this formatting by specifying end='-'
.
1area = 1232central_office = 4563sub_code = 789045print('Client Phone Number')6print(area,end='-')7print(central_office, end='-')8print(sub_code)
1Client Phone Number2123-456-7890