本文主要是介绍python类型之string上篇,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用单引号
string1 = 'This is a string in single quotes.'
print(string1)
使用双引号
string2 = "This is a string in double quotes."
print(string2)
使用三引号(多行字符串)
string3 = '''This is a multi-linestring in triple quotes,this is end line '''print(string3)
字符串可以进行连接(拼接)
string5 = "Hello, " + "world!"
格式化
使用 % 操作符
单个参数
name = "Kimi"
greeting = "Hello, %s!" % name
多个参数
name = "Kimi"
hobby = "football"
greeting = "Hello, %s , %s" % (name,hobby)
print(greeting)
字典类型参数
name = "Kimi"
age = 30greeting = "Hello, %(name)s. You are %(age)d years old." % {'name': name, 'age': age}
print(greeting)
使用 str.format()
greeting = "Hello, {}!".format(name)
使用 f-string
Python 3.6+ 进行格式化
greeting = f"Hello, {name}!"
注意事项
- 从 Python 2.6 开始,推荐使用 str.format() 方法
- 格式化字符串字面量(也称为 f-string从 Python 3.6 开始支持)进行字符串格式化,因为它们更灵活、更易于阅读。
- 在使用 % 操作符时,如果参数的数量和格式字符串中的占位符不匹配,将会引发错误
这篇关于python类型之string上篇的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!