Python Print
1. Print
Ex1 Print Basic Interger and String
1 | str_name= "hello" |
output:
str value is hello, and number is 999
%-formatting-OLD
Example 1 Print String with %
Operator
1 | text = 'world' |
output:
hello world
hello world
Hello, Test. You are 100.
3. str.format()- NEW
str.format() 是對 %-formatting 的改進,可以用函式呼叫語法,可以通過 format() 方法對被轉換為字串的物件
ex1: Print Basic String
1 | text = 'world' |
ex2 print dict字典 with **
1 | person = {'name': 'Eric', 'age': 74} |
output
Hello, Eric. You are 74.
ex3: print X decimal places
1 | float = 2.154327 |
output:
2.15
ex4: print decimal format
1 | number = 1.345 |
output:
1.3
1.34
1.345
Ex5: 轉16進位
print('{:x}'.format(23))
output:17
4 printf - New
Ex1 Print Basic String
1 | text = 'world' |
output:
Hello world
25
Ex2 Print Basic Integer
1 | x = 10 |
Ex3 Print X decimal places
print 2 decimal places
1
2now_value=123.456
print(f'{now_value:.2f}')output:
123.46
Comma between number, and print 2 decimal places
1
2number=1000000
print(f'The number, 1000000, format with a comma {number:,.2f}')output:
The number, 1000000, format with a comma 1,000,000.00
Ex4 Date and Time
1 | from datetime import datetime |
Ex5 Runtime time
1 | import time |
5 other print function
Ex1: round number:
1 | number = 1.345 |
Ex2: tab
print(('===\t=========== \t =========== \t =========== \n').expandtabs(8))
output:
=== =========== =========== ===========
Ex3: lower String
1 | name = "Ja Laaaa" |
output:
ja laaaa is funny.
6 Print List
There are couple of ways to print list
test = ['A' , 'B', 'C' , 'D']
- Method 1: using for loop
1
2
3
4for i in test:
print(i,end=' ')
print()
# A B C D - Method 2: *listname unpack list
We can use without for loop to unpack listprint(*test) # A B C D
Print new line:
print(*test, sep=’\n’)