
“理论上,理论和实践没有区别。但实践上,是有区别的。”
——–Jan L.A. van de Snepscheut
如果字符串跨越一行以上,可以使用三引号:
>>> """第一行
... 第二行
... 第三行"""
'第一行\n第二行\n第三行'
>>> "第一行
... 第二行
... 第三行"
File "<input>", line 1
"第一行
^
SyntaxError: EOL while scanning string literal
与列表和元组一样,字符串也是可迭代的。可使用索引查找字符串中的每个字符。与其他可迭代对象一样,字符串中第一个字符所在的索引为0,其后每个索引递增1。
>>> author = "Zhou Shuren"
>>> author[0]
'Z'
>>> author[1]
'h'
>>> author[2]
'o'
>>> author[3]
'u'
>>> author[4]
' '
>>> author = "Kafka"
>>> author[-1]
'a'
>>> author[-2]
'k'
>>> author[-3]
'f'
字符串和元组一样都是不可变的,无法修改字符串中的字符。如果想要修改,就必须创建一个新的字符串:
>>> ff = "apple"
>>> ff = "it's an apple"
字符串拼接
作用:将两个或多个字符串组合在一起
>>> "cat" + "in" + "hat"
'catinhat'
>>> "cat" + " in" + " hat"
'cat in hat'
字符串乘法
作用:将两个或多个字符串组合在一起
>>> "apple"*3
'appleappleapple
改变大小写
作用:更改大小写
>>> "We are the world!"
'We are the world!'
>>> "We are the world!".upper()
'WE ARE THE WORLD!'
>>> "We are the world!".lower()
'we are the world!
# capitalize方法将字符串的首字母改写为大写
>>> "how are you?".capitalize()
'How are you?'
格式化
作用:把字符串中的“{ }”替换为传入的字符串
>>> "Zhou {}".format("Shuren")
'Zhou Shuren'
# 也可以把变量作为参数传递
>>> name = "Shuren"
>>> "Zhou {}".format(name)
'Zhou Shuren'
# 花括号可重复使用
>>> "{} Shu{}".format("Zhou","ren")
'Zhou Shuren'
# 脚本
n1 = input("enter a noun:")
v = input("enter a verb:")
adj = input("enter an adj:")
n2 = input("enter another noun:")
r = "The {} is {}. {} also {} it.".format(n1,adj,n2,v)
print(r)
# 运行结果
D:\python\untitle\Scripts\python.exe C:/Users/17264/Desktop/chapter_3.py
enter a noun:apple
enter a verb:enjoys
enter an adj:sweet
enter another noun:John
The apple is sweet. John also enjoys it.
进程已结束,退出代码0
分割
作用:把字符串中的“{ }”替换为传入的字符串
>>> "How are you?!Fine,thank you.".split("!")
['How are you?', 'Fine,thank you.']
连接
作用:把字符串中的“{ }”替换为传入的字符串
# 传入参数为字符串
>>> a = "abc"
>>> result = "+".join(a)
>>> result
'a+b+c'
# 传入参数为字符串列表
>>> words = ["the","apple","is","red"]
>>> "".join(words)
'theappleisred'
>>> " ".join(words)
'the apple is red'
去除空格
作用:去除字符串开头和末尾的空白字符
>>> s = " The day is sunny. "
>>> s.strip()
'The day is sunny.'
替换
作用:用第二个参数替换原字符串中所有与第一个字符串一样的内容
>>> equ = "all animals are equal"
>>> equ = equ.replace("a","@")
>>> print(equ)
'@ll @nim@ls @re equ@l'
查找索引
作用:获得字符串中某个字符第一次出现的索引
>>> "animals".index("i")
2
>>> "animals".index("z")
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: substring not found
>>> try: "animals".index("z")
... except: print("Not Found.")
...
Not Found.
in关键字
作用:检查某个字符串是否在某个字符串中
>>> "cat" in "the cat is so cute!"
True
>>> "cat" not in "the cat is so cute!"
False
换行符
作用:换行
>>> print("line1\nline2\nline3")
line1
line2
line3
切片
作用:提取可迭代对象中元素的子集
注意:切片时包含起始索引位置的元素,但不包含结束索引位置的元素
# 列表切片
>>> fruits = ["apple","watermelon","strawberry","banana"]
>>> fruits[0:3]
['apple', 'watermelon', 'strawberry']
# 字符串切片
>>> "the apple is so sweet."[4:9]
'apple'
>>> "the apple is so sweet."[13:]
'so sweet.'
转义
作用:将“\”置于某个双引号前,可告诉python将该双引号识别的普通字符
>>> "She said "Surely.""
File "<input>", line 1
"She said "Surely.""
^
SyntaxError: invalid syntax
>>> "She said \"Surely.\""
'She said "Surely."'
如果在单引号中使用双引号,或者在双引号中使用单引号,则不需要进行转义,更加简单。
转载请注明:XAMPP中文组官网 » Python编程教程4:字符串操作