>>> name = 'Top' >>> f'Hello, {name}!' 'Hello, Top!'
也可以嵌入Python表达式:
1 2 3 4 5
>>> a = 5 >>> b = 10 >>> f'Five plus ten is {a + b} and not {2 * (a + b)}.' 'Five plus ten is 15 and not 30.' >>>
用在函数中:
1 2 3 4 5 6
>>> defgreet(name, question): ... returnf"Hello, {name}! How's it {question}?" ... >>> >>> greet('Top', 'going') "Hello, Top! How's it going?"
也支持format()方法所使用的字符串格式化语法:
1 2 3 4
>>> name = 'Top' >>> errno = 50159747054 >>> f"Hey {name}, there's a {errno:#x} error!" "Hey Top, there's a 0xbadc0ffee error!"
模板字符串
1 2 3 4 5 6 7 8
>>> name = 'Top' >>> errno = 50159747054 >>> >>> from string import Template >>> t = Template('Hello, $name!') >>> t.substitute(name=name) 'Hello, Top!' >>>
但是模板字符串不能使用格式说明符,需要将errno转换为十六进制字符串:
1 2 3 4
>>> tmp = 'Hello $name, there is a $errno error!' >>> Template(tmp).substitute(name=name, errno=hex(errno)) 'Hello Top, there is a 0xbadc0ffee error!' >>>