设为首页 加入收藏

TOP

python3字符串格式化format()函数的简单用法
2018-12-07 10:08:48 】 浏览:62
Tags:python3 字符串 格式 format 函数 简单 用法

format()函数

"""
测试 format()函数
"""

def testFormat():
    # format()函数中有几个元素,前面格式化的字符串中就要有几个 '{}'
    # 位置
    s1 = 'a{}b{}c{}d{}'.format(1, 2, 3, 4)
    # 索引,format()函数中的元素,从0开始
    s2 = 'a{0}b{1}c{3}d{2}'.format(1, 2, 3, 4)
    # 索引可以重复使用
    s3 = 'a{0}b{1}c{0}d{1}'.format(1, 2, 3, 4)
    print('-' * 8)
    print('一般用法:')
    print(s1)
    print(s2)
    print(s3)
    print('-' * 8)

    # format()函数中元素个数,和前面的字符串中的'{}'个数不相同
    # 格式化字符串中的'{}'里面必须要有后面format()函数中元素的索引
    s4 = 'a{0}b{1}cd'.format(1, 2, 3, 4)
    s5 = 'a{0}b{1}c{0}d{1}e{1}f{1}g{1}h{1}{4}{4}{4}{4}{5}{4}{4}{4}{4}'.format(1, 2, 3, 4, '*', '哈哈,这是第6个数,索引是5')
    print('其他用法:')
    print(s4)
    print(s5)
    print('-' * 8)
    return

if __name__ == '__main__':
    testFormat()

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇撩课-Python-每天5道面试题-第7天 下一篇Python基本数据类型

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目