Python 字符串
字符串
python中的字符串是由单引号或双引号括起。
'hello'
与"hello"
相同。
您可以使用以下print()
函数显示字符串:
给变量赋字符串类型值
将字符串赋值给变量是使用变量名称后跟等号和字符串完成的:
多行字符串
您可以使用三个引号将多行字符串分配给变量:
实例
三个双引号
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
或者三个单引号:
实例
三个单引号
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
注意:在三个引号中字符可以换行
字符串是数组
与许多其他流行的编程语言一样,Python中的字符串是表示unicode字符的字节数组。
但是,Python没有字符数据类型,单个字符只是一个长度为1的字符串。方括号可用于访问字符串的元素。
实例
split() 方法按指定的分割符将字符串拆分为多个子字符串:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
print(a.split(",")) # returns ['Hello', ' World!']
了解有关字符方法:
请访问:字符串参考
字符串格式
在python变量章节学到的,不能把字符串与数字按如下方式组合:
但是我们可以使用format()
方法组合字符串和数字!
format()
方法接受传递的参数,格式化它们,并将它们放在占位符所在的字符串中 {}
:
实例
使用format()
方法将数字插入字符串:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
txt = "My name is John, and I am {}"
print(txt.format(age))
format()
方法接受参数不限数量的,并放在对应占位符中:
实例
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
可以使用索引编号{0}
来确保参数放在正确的占位符中:
实例
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))