python基础1:打印三角形 * ---- 字符串居中显示 str.center( N )

字符串居中显示:

  • 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!

请输入英文语句2do 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? |
|                                       |
+---------------------------------------+
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值