字串 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!!!