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() 格式化數字的多種方法:


最後說一下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'))

效果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章