Python基础 第三章 使用字符串(1)精简版

所有标准序列操作(索引,切片,乘法,成员资格检查,长度,最小值,最大值)都适于字符串。

但,字符串是不可变得,故所有得元素赋值和切片赋值都是非法的。

1. %s 转换说明符 设置字符串格式

%左边指定一个字符串,右边指定要设置其格式的值(可使用单个值[如字符串或数字],可使用元组[设置多个值得格式],还可使用字典)

1 formats = "Hello, %s! %s enough for you?"
2 value = ('world', 'Hot')
3 final_format = formats % value
4 print(final_format)
5 结果:
6 Hello, world! Hot enough for you?

2. 模板字符串(类似UNIX shell得语法)

在字符串得格式设置中,可将关键字参数视为一种向命名替换字段提供值得方式。

如下,包含等号的参数称为关键字参数

1 from string import Template
2 tmpl = Template("Hello, $who! $what enough for you?")
3 tmpl_final = tmpl.substitute(who="Mars", what="Dusty")
4 print(tmpl_final)
5 结果:
6 Hello, Mars! Dusty enough for you?

3. 字符串方法format(编码新时代,推荐使用!!!)

每个替换字段都用花括号括起,其中可能包含名称,还可能包含有关如何对相应值进行转换和格式设置的信息。

 1 str = "{}, {} and {}".format("first", "second", "third")
 2 print(str)
 3 结果:first, second and third
 4 
 5 str1 = "{0}, {1} and {2}".format("first", "second", "third")
 6 print(str1)
 7 结果:first, second and third
 8 
 9 str2 = "{3} {0} {2} {1} {3} {0}".format("be","not","or","to")
10 print(str2)
11 结果:to be or not to be
关键字参数的排列顺序无关紧要;
可指定格式说明符 .2f,并使用冒号将其与字段名隔开。
 1 from math import pi,e
# 关键字参数的排列顺序无关紧要。指定了格式说明符 .2f,并使用冒号将其与字段名隔开
2 str = "{name} is approximately {value:.2f}!".format(value=pi, name="π") 3 print(str) 结果: π is approximately 3.14!
若变量与替换字段同名,用如下方式简写:在字符串前面加上f。
 1 from math import pi,e
 2 
 3 # 若变量与替换字段同名,用如下方式简写:在字符串前面加上f
 4 str1 = f"Euler's constant is roughly {e}!"
 5 print(str1)
 6 
 7 # 等价表达式
 8 str2 = "Euler's constant is roughly {e}!".format(e=e)
 9 print(str2)
10 
11 结果:
12 Euler's constant is roughly 2.718281828459045!
13 Euler's constant is roughly 2.718281828459045!

3.3 设置字符串的格式:完整版 ——后续再学习/P43

猜你喜欢

转载自www.cnblogs.com/ElonJiang/p/11318936.html
今日推荐