使用字符串

所有的序列操作都是都是用于字符串。(索引、切片、乘法、长度)

但是因为字符串是不可变的,因此所有的元素赋值和切片赋值都是非法错误。

设置字符串的格式:精简版

以下是python中字符串格式的一些基本的用法,初学者的我了解这些已经够用了。

 1 format = 'Hello, %s. %s enough for you?'
 2 values = ('world', 'hot')
 3 print(format % values)
 4 
 5 from string import Template
 6 templ = Template('Hello, $who! $what enough for ya?')
 7 print(templ.substitute(who = 'Eric', what = 'money'))
 8 
 9 print('{}, {} and {}'.format('a', 'b', 'c'))
10 
11 print('{1}, {0} and {2}'.format('a', 'b', 'c'))
12 
13 from math import pi
14 print('{name} is approximately {value:.2f}.'.format(name = 'Π', value = pi))
15 
16 from math import e
17 print(f'Euler\'s constant is roughly {e}')

自己猜猜它们每一块的执行结果吧。

看看自己是否猜得对:

Hello, world. hot enough for you?
Hello, Eric! money enough for ya?
a, b and c
b, a and c
Π is approximately 3.14.
Euler's constant is roughly 2.718281828459045

猜你喜欢

转载自www.cnblogs.com/FunkyEric/p/10362847.html