## 本文基于Python3,可能存在部分内容不适配Python2
1. 最简单的字符串的输出:
str1 = 'popma is so cool'
print(str1)
输出:
popma is so cool
2. '%S'格式化字符串输出:
格式化字符串时,字符串中有格式符,字符串就变成一个模板了;
例如:
str2 = '%s is so cool' %'popma'
print(str2)
输出还是像上面的一样,可以试试看。
但是如果有多个格式符,如何处理呢?Python用一个tuple(元组,如果还没有学习Python数据结构的可能不容易理解)将多个值传递给模板,和格式符一一对应。
例如:
str3 = '%s is %d' %('popma', 20)
print(str3)
其中'%d'表示数字,这个和C里一样。
3. format函数
3.1. 通过位置映射:
举例子说明:
'{0} is {1}, he is a {2} ------ {0}'.format('popma',20,'boy')
Out:
'popma is 20, he is a boy ------ popma'
还有一种不写0和1的:
'{} is {}, he is a {}'.format('popma',20,'boy')
Out:
'popma is 20, he is a boy'
3.2. 通过类似字典映射:
'I am {name}, I am {age}'.format(name='popma', age=20)
Out:
'I am popma, I am 20'
本文深入讲解Python中字符串的输出及格式化方法,包括简单的字符串输出、使用格式化字符串输出以及利用format函数进行复杂格式化。文章详细介绍了不同格式化方式的特点和应用,适合初学者和进阶者学习。

2033

被折叠的 条评论
为什么被折叠?



