Python学习笔记 | 字符串分隔、格式化输出

一、案例

计算基础代谢率bmr

二、知识点

1、字符串分割-split

  • 写法:str.split(‘分隔符’)
  • 方式:按逗号;按空格
  • 在整个字符串中找某个字符位置:str.find(‘男’)
  • 查看类型的函数:type()
  • 其余用法https://docs.python.org/3/library/stdtypes.html#str.split

下面是Python Console:

#	分隔符为空格
>>> input_str = '男 65 180 23'   #找到字符串被某个部分的位置用input_str.find('男')  输出为0
>>> input_str.split(' ')
>>> ['男','65','180','23']
>>> l = input_str.split(' ')
>>> type(l)						#查看类型的函数type()
>>> list
#	分隔符为逗号
>>> input_str = '男,65,180,23'
>>> input_str.split(',')
>>> ['男' ,'65','180','23']

2、格式化输出-format

  • 写法:print(’{}, {}, {}, {}’.format(gender, weight, height, age))
    print(’{0}, {1}, {2}, {3}’.format(gender, weight, height, age))
    默认顺序,也可乱排

下面是Python Console:

>>> print('{1}, {0}'.format(70,100))
>>> 100,70
>>> print('您的性别:{0},  体重:{1}公斤, 身高:{2}厘米, 年龄:{3}岁'.format(gender, weight, height, age))     
>>> 您的性别:男, 体重:65公斤, 身高:180厘米, 年龄:23

三、python代码

def main():
    """
        主函数
    """
    y_or_n = input('是否退出程序(y/n)')
    while y_or_n != 'y':
       print('请输入以下信息,用空格分割')
       input_str = input('性别,体重(kg),身高(cm),年龄')
       str_list = input_str.split(' ')                               #对字符串分割,用空格
       gender = str_list[0]
       weight = float(str_list[1])                                   #数据类型转化
       height = float(str_list[2])
       age = int(str_list[3])

       if gender == '男':
           bmr = (13.7 * weight) + (5.0 * height) - (6.8 * age) + 66
       elif gender == '女':
           bmr = (9.6 * weight) + (1.8 *height) - (4.7 * age) + 655
       else:
           bmr = -1

       if bmr != -1:
           #格式化输出。{}里也可以填0123对应format里面的位置
           print('您的性别:{},  体重:{}公斤, 身高:{}厘米, 年龄:{}岁'.format(gender, weight, height, age))     
           print('您的基础代谢率:{}大卡'.format(bmr))
       else:
           print('暂不支持该性别')
       print()
       y_or_n = input('是否退出程序(y/n)')

if __name__ == '__main__':
    main()

版权声明:本文为weixin_44878159原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。