字符串居中顯示:
- str.center( N ): S.center(width[, fillchar]) -> st 居中顯示,N 代表字符串str所在行的總字節數
- str.ljust(): S.ljust(width[, fillchar]) -> str 左對齊,可用fillchar填充空位
- dir(str): 返回str的屬性和方法
CODE1:
x = int(input('請輸入三角形所佔行數:'))
n = int(input('請輸入三角形離左側的字節數:'))
for i in range(x):
# 每行星星數
num = (2*i + 1)*'*'
# print(num.center(2*n+x))
print(' '*n, num.center(2*x-1))
output1:
請輸入三角形所佔行數:5
請輸入三角形離左側的字節數:9
*
***
*****
*******
*********
CODE2:
'''
輸入三行文字,讓這三行文字在一個方框內居中顯示
如輸入(不要輸入中文):
hello tarena!
my name is weimingzi
good bye
輸出:
+-----------------------+
| hello tarena |
| my name is weimingze |
| good bye |
+-----------------------+
'''
cont1 = input('請輸入英文語句1:')
cont2 = input('請輸入英文語句2:')
cont3 = input('請輸入英文語句3:')
# input的長度
size1 = len(cont1)
size2 = len(cont2)
size3 = len(cont3)
# 確定框的長度
len_head = max(size1+4, size2+4, size3+4)
# 輸出前兩行 框
head1 = '+' + '-'*(len_head-2) + '+'
head2 = '|' + ' '*(len_head-2) + '|'
print(head1,head2, sep='\n')
# 居中輸出內容
output1 = '|' + cont1.center(len_head-2) + '|'
output2 = '|' + cont2.center(len_head-2) + '|'
output3 = '|' + cont3.center(len_head-2) + '|'
print(output1, output2, output3,sep='\n')
print(head2,head1, sep='\n')
output2:
請輸入英文語句1:hello, it's a good day!
請輸入英文語句2:do you have plan to do something?
請輸入英文語句3:basketball, or football? is this ok?
+---------------------------------------+
| |
| hello, it's a good day! |
| do you have plan to do something? |
| basketball, or football? is this ok? |
| |
+---------------------------------------+