立即学习:https://edu.csdn.net/course/play/26755/340104?utm_source=blogtoedu
python 中格式化字符串的方式:
1,%
2,模板字符串
3,字符串的format方法
4,fstring
模板字符串介绍:
通过Template对象封装,$放置一些占位符,并通过substitute方法用实际的值替换这些占位符
实例代码:
from string import Template
template1 = Template('$s 是我最喜欢的语言,$s 既简单又好学')
print(template1.substitute(s='Python'))
# 如果占位符后面是英文,如何进行区分?({}将名称括起来)
template2 = Template('${h}ello, world')
print(template2.substitute(h='h'))
# 如果想输出占位符$,怎么办?(使用两次$)
template3 = Template('$hi, $$, $my name is xx')
print(template3.substitute(hi='你好', my='my'))
# 还可以使用字典直接作为参数
my_dic = {}
my_dic['hi'] = '你好'
my_dic['my'] = 'my'
print(template3.substitute(my_dic))
fstring 方法介绍:(Python版本需在3.6以后)
在字符串中直接使用Python变量,但需要在字符串前面用f标注
实例代码:
name = 'Bob'
age = 20
def getAge()
return 21
s = f'我是{name}, 我今年{age}岁,明年我就{getAge()}岁了。'
print(s)