《python基础教程》笔记(二)
- Python没有专门用于表示字符的类型,因此一个字符就是只包含一个元素的字符串
- 对于字符串字面量(以及其他的序列字面量),可直接对其执行索引操作,无需先将其赋给变量。这与先赋给变量再对变量执行索引操作的效果是一样的。
>>> 'Hello'[1]
'e'
>>> fourth = input('Year: ')[3]
Year: 2005
>>> fourth
'5'
3. 字符串格式设置:
- 字符串格式设置运算符:%,在%左边指定一个字符串(格式字符串),并在右边指定要设置其格式的值。指定要设置其格式的值时,可使用单个值(如字符串或数字),可使用元组(如果要设置多个值的格式),还可使用字典。
>>> format = "Hello, s. s enough for ya?" % %
>>> values = ('world', 'Hot')
>>> format values %
'Hello, world. Hot enough for ya?'
- 模板字符串
>>> from string import Template
>>> tmpl = Template("Hello, $who! $what enough for ya?")
>>> tmpl.substitute(who="Mars", what="Dusty")
'Hello, Mars! Dusty enough for ya?'
- format
>>> "{}, {} and {}".format("first", "second", "third")
'first, second and third'
>>> "{0}, {1} and {2}".format("first", "second", "third")
'first, second and third'
>>> "{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to")
'to be or not to be'
>>> from math import pi
>>> "{name} is approximately {value:.2f}.".format(value=pi, name="π")
'π is approximately 3.14.'
>>> from math import e
>>> f"Euler's constant is roughly {e}."
"Euler's constant is roughly 2.718281828459045."