In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
本篇内容主要讲解"有哪些Python格式化字符串的方法",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"有哪些Python格式化字符串的方法"吧!
1. %-formatting格式化字符串
最早的格式化是用%(百分号), 它这么用:
In : name = 'World' In : id = '10' In : 'Hello %s,id=%s' %(name,id) Out: 'Hello World,id=10'
这里用的%s表示格式化成字符串,另外常用的是%d(十进制整数)、%f(浮点数)。
另外也支持使用字典的形式:
In : 'Hello[%(name)s],id=%(name)s' % {'id': 10, 'name': 'World'} Hello[World],id=10
2. str.format()格式化字符串
常规用法
In : name = 'World' In : 'Hello {}' %(name) Out: 'Hello World'
通过位置访问:
In : '{2}, {1}, {0}'.format('a', 'b', 'c') Out: 'c, b, a'
通过关键字访问:
In : 'Hello {name}'.format(name='testerzhang') Out: 'Hello testerzhang'
3. f-string格式化字符串
Python3.6 版本开始出现了此新的格式化字符串,性能又优于前面两种方式。
In : name = "testerzhang" In : print(f'Hello {name}.') In : print(f'Hello {name.upper()}.') Out: Hello testerzhang. Out: Hello TESTERZHANG. In : d = {'id': 1, 'name': 'testerzhang'} In : print(f'User[{d["id"]}]: {d["name"]}') Out: User[1]: testerzhang
注意:如果低于Python3.6,可以通过pip install future-fstrings即可,在相应的py 脚本文件里不需要加import这个库,但是需要头部加上# coding: future_fstrings。
到此,相信大家对"有哪些Python格式化字符串的方法"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.