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

2023-07-29,,

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

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

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

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

 formats = "Hello, %s! %s enough for you?"
value = ('world', 'Hot')
final_format = formats % value
print(final_format)
结果:
Hello, world! Hot enough for you?

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

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

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

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

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

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

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

 # 若变量与替换字段同名,用如下方式简写:在字符串前面加上f
str1 = f"Euler's constant is roughly {e}!"
print(str1) # 等价表达式
str2 = "Euler's constant is roughly {e}!".format(e=e)
print(str2) 结果:
Euler's constant is roughly 2.718281828459045!
Euler's constant is roughly 2.718281828459045!

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

Python基础 第三章 使用字符串(1)精简版的相关教程结束。

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

下载本文的Word格式文档,以方便收藏与打印。