Python标准库(4)—— string

String的常规用法就不多做介绍了,事实上String中提供的很多函数已经移植为 str对象的方法,实际用到该模块的地方不多。

这里只介绍一下format和template,都是Python中字符串替换的方法。

如果是简单的字符串替换,可以使用格式化符或者format替代。

# 使用格式化符
print("hello, %s, age is %d, score is %.2f" % ("guodabao", 29, 54.3333))

# 使用format方式一
print("hello, {}, age is {}, score is {:.2f}".format("guodabao", 29, 54.3333))

# 使用format方式二
d = {"name": "guodabao", "age": 29, "score": 54.3333}
print("hello, {name}, age is {age}, score is {score:.2f}".format(**d))

# 格式化数字的方法
print("hello, {name}, age is {age:0>5d}, score is {score:.2e}".format(name="guodabao", age=29, score=54.3333))

借用一下菜鸟教程中的str.format() 格式化数字的多种方法:


1620891157595.jpg

最后说一下template,也是一种字符串替换的方法。

substitute:执行模板替换,返回一个新字符串。

safe_substitute:类似substitute,不同之处是如果有占位符找到,将原始占位符不加修改地显示在结果字符串中。

  from string import Template
  
  
  t = Template('$who like $what')
  print(t.substitute(who='guodabao', what='apple'))
  print(t.safe_substitute(who='guodabao'))

效果:


1620892078586.jpg

你可能感兴趣的:(Python标准库(4)—— string)