字串 string
Python 基础: 字串 string
replace 取代字串
text = "Hello {name}"
print(text.replace('{name}', 'KJ'))
# Hello KJ
format 格式化字串
字串取代
text = "Hello {name}, this {price:.2f} dollars is for you!"
print(text.format(name='KJ', price = 49))
# Hello KJ, this 49.00 dollars is for you!
转换 16 进制
text = "Hello {name}, this {price:x} dollars is for you!"
print(text.format(name='KJ', price = 49))
# Hello KJ, this 31 dollars is for you!
translate 翻译字串
# 翻译来源
translate_source = "aeiou"
# 翻译目标
translate_target = "AEIOU"
# 翻译表
translate_mapping = str.maketrans(translate_source, translate_target)
# 翻译字串
text = "this is string example....wow!!!"
print(text.translate(translate_mapping))
# thIs Is strIng ExAmplE....wOw!!!