最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

Python编程教程4:字符串操作

XAMPP案例 admin 911浏览 0评论
0Python

“理论上,理论和实践没有区别。但实践上,是有区别的。”

                      ——–Jan L.A. van de Snepscheut

字符串操作
1

三引号
如果字符串跨越一行以上,可以使用三引号:

>>> """第一行
... 第二行
... 第三行"""
'第一行\n第二行\n第三行'

>>> "第一行
... 第二行
... 第三行"
  File "<input>", line 1
    "第一行
       ^
SyntaxError: EOL while scanning string literal
如果使用单引号或双引号定义一个跨行的字符串,Python会报告语法错误。
2

索引
与列表和元组一样,字符串也是可迭代的。可使用索引查找字符串中的每个字符。与其他可迭代对象一样,字符串中第一个字符所在的索引为0,其后每个索引递增1。

>>> author = "Zhou Shuren"
>>> author[0]
'Z'
>>> author[1]
'h'
>>> author[2]
'o'
>>> author[3]
'u'
>>> author[4]
' '
Python还支持使用负索引查找列表中的元素:可以用来从右向左查找可迭代对象中元素的索引(必须是一个负数)。使用索引-1可以查找可迭代对象中的最后一个元素,示例如下:
>>> author = "Kafka"
>>> author[-1]
'a'
>>> author[-2]
'k'
>>> author[-3]
'f'
负索引-2查找的是倒数第二个元素,负索引-3查找的是倒数第三个元素,以此类推。
3

字符串是不可变的

字符串和元组一样都是不可变的,无法修改字符串中的字符。如果想要修改,就必须创建一个新的字符串:

>>> ff = "apple"
>>> ff = "it's an apple"
但Python提供了多个从已有字符串中创建新字符串的方法:

字符串拼接

1
工具:加法操作符

作用:将两个或多个字符串组合在一起

>>> "cat" + "in" + "hat"
'catinhat'
>>> "cat" + " in" + " hat"
'cat in hat'
悄悄题外话:合并列表也是用的加法操作符哦~

字符串乘法

2
工具:乘法操作符

作用:将两个或多个字符串组合在一起

>>> "apple"*3
'appleappleapple

改变大小写

3
工具:方法: .xxx()

作用:更改大小写

>>> "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?'

格式化

4
工具:format方法

作用:把字符串中的“{ }”替换为传入的字符串

>>> "Zhou {}".format("Shuren")
'Zhou Shuren'

# 也可以把变量作为参数传递
>>> name = "Shuren"
>>> "Zhou {}".format(name)
'Zhou Shuren'

# 花括号可重复使用
>>> "{} Shu{}".format("Zhou","ren")
'Zhou Shuren'
如果要根据用户输入来创建字符串,format方法很有用。示例如下:
# 脚本
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

分割

5
工具:split方法,需要传入一个字符串作为split方法的参数

作用:把字符串中的“{ }”替换为传入的字符串

>>> "How are you?!Fine,thank you.".split("!")
['How are you?', 'Fine,thank you.']

连接

6
工具:join方法

作用:把字符串中的“{ }”替换为传入的字符串

# 传入参数为字符串
>>> a = "abc"
>>> result = "+".join(a)
>>> result
'a+b+c'
# 传入参数为字符串列表
>>> words = ["the","apple","is","red"]
>>> "".join(words)
'theappleisred'
>>> " ".join(words)
'the apple is red'

去除空格

7
工具:stripe方法

作用:去除字符串开头和末尾的空白字符

>>> s = "    The day is sunny.    "
>>> s.strip()
'The day is sunny.'

替换

8
工具:replace方法

作用:用第二个参数替换原字符串中所有与第一个字符串一样的内容

>>> equ = "all animals are equal"
>>> equ = equ.replace("a","@")
>>> print(equ)
'@ll @nim@ls @re equ@l'

查找索引

9
工具:index方法

作用:获得字符串中某个字符第一次出现的索引

>>> "animals".index("i")
2
>>> "animals".index("z")
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: substring not found
如果index方法没有找到匹配的结果,Python会报告异常错误。这时采用前面学习过的异常处理方法来解决:
>>> try: "animals".index("z")
... except: print("Not Found.")
... 
Not Found.

in关键字

10
工具:in或not in关键字

作用:检查某个字符串是否在某个字符串中

>>> "cat" in "the cat is so cute!"
True
>>> "cat" not in "the cat is so cute!"
False

换行符

11
工具:在字符串加入\n

作用:换行

>>> print("line1\nline2\nline3")
line1
line2
line3

切片

12
工具:【可迭代对象】【[起始索引:结束索引]】

作用:提取可迭代对象中元素的子集

注意:切片时包含起始索引位置的元素,但不包含结束索引位置的元素

# 列表切片
>>> 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.'

转义

13
工具:\

作用:将“\”置于某个双引号前,可告诉python将该双引号识别的普通字符

>>> "She said "Surely.""
  File "<input>", line 1
    "She said "Surely.""
               ^
SyntaxError: invalid syntax
>>> "She said \"Surely.\""
'She said "Surely."'

如果在单引号中使用双引号,或者在双引号中使用单引号,则不需要进行转义,更加简单。

转载请注明:XAMPP中文组官网 » Python编程教程4:字符串操作

您必须 登录 才能发表评论!