一、字符串基本操作
字符串(String)是一种Python基本数据类型,是由字符组成的序列,可以使用单引号或双引号将其括起来。字符串是一种不可变的数据类型,意味着一旦创建,就不能直接修改其中的字符。但是,你可以使用各种操作和方法来处理和操作字符串。
1、创建字符串
Python中,使用单引号(')或双引号(")来创建字符串,也可以使用三引号(''')创建多行字符串。
(1)使用单引号:
string1 = 'hello world'
(2)使用双引号:
string2 = "hello world"
(3)使用三引号(用于多行字符串):
string3 = '''hello world'''
注意:单引号和双引号都可以用于创建普通字符串,但如果字符串本身包含单引号或双引号,则应该使用另一种引号,例如:
string4 = "I'm a string with an apostrophe" string5 = 'He said, "Hello world!"' string4 = "I'm a string with an apostrophe" string5 = 'He said, "Hello world!"'
2、字符串长度
注意:单引号和双引号都可以用于创建普通字符串,但如果字符串本身包含单引号或双引号,则应该使用另一种引号,例如:
string4 = "I'm a string with an apostrophe" string5 = 'He said, "Hello world!"'
2、字符串长度
在Python中,要获取一个字符串的长度,可以使用内置函数len()。len()函数返回字符串中字符的数量(包括空格和特殊字符)。
my_string = "Hello, world!" print(len(my_string)) # 输出 13
3、拼接字符串
在 Python 中,我们可以使用加法操作符 +
来拼接字符串。
str1 = 'Hello' str2 = 'world' str3 = str1 + ' ' + str2 print(str3) # 输出:Hello world
4、字符串的索引和切片操作
Python 中,字符串也是一种序列类型,因此支持序列操作。
(1)使用索引访问字符串中单个元素:
索引指的是使用单个下标访问字符串中的某个字符,其语法为 string[index]
,其中 index
表示要访问的字符在字符串中的位置。Python 中的索引从0开始,表示字符串中第一个字符,以此类推。
例如:
string = 'Hello, world!' print(string[1]) # 输出:e print(string[7]) # 输出:w
(2)使用切片访问字符串中的字串:
切片指的是提取字符串中的一个子串,其语法为 string[start:end:step]
,其中 start
表示起始位置(包含),end
表示结束位置(不包含),step
表示步长,默认值为1。当省略 start
或 end
参数时,分别默认为字符串开头和结尾。当省略 step
参数时,默认为1。
例如:
string = 'Hello, world!' print(string[0:5]) # 输出:Hello print(string[7:]) # 输出:world! print(string[::2]) # 输出:Hlo ol!
5、格式化字符串
Python 的字符串格式化有三种常见方式:百分号(%)格式化、str.format()方法、f-string表达式。
(1)%占位符
使用百分号(%)作为占位符,最初的版本。
例如:
age = 18name = 'Tom' print('My name is %s, and I am %d years old.' % (name, age))
输出:
My name is Tom, and I am 18 years old.
其中 %s
表示字符串类型,%d
表示整数类型,%f
表示浮点型。%d
和 %f
后面可以加上 .n
,表示保留 n 位小数。当需要在字符串中表示 %
字符时,需要用两个百分号转义。
(2)str.format()方法
使用 str.format()
方法,此方法可以使用花括号 {}
作为占位符,python2.6版本引入。
例如:
age = 18name = 'Tom' print('My name is {}, and I am {} years old.'.format(name, age))
输出:
My name is Tom, and I am 18 years old.
注意,{}
中可以加入数字,表示占位符的顺序。
例如:
print('{1} is {0} years old.'.format(age, name))
输出:
Tom is 18 years old.
(3)f-string表达式
f-string表达式,可以解析任意类型的数据,运行的时候渲染,性能比%,.format()更好,python3.6版本引入。
例如:
age = 18name = 'Tom' print(f'My name is {name}, and I am {age} years old.')
输出:
My name is Tom, and I am 18 years old.
二、字符串的属性方法
Python中可以使用内置函数dir()
来查看对象具有的属性和方法。这个内置函数会返回一个列表,列表中包含了该对象所拥有的所有属性、方法和特殊方法。
C:\Users\057776>python Python 3.8.8 (tags/v3.8.8:024d805, Feb 19 2021, 13:18:16) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> dir(str) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
关于字符串的属性方法详见官网:字符串的方法 — Python 3.8.16 文档 ,下面介绍一些字符串的常见方法。
1、字符串编码和解码
Python中的encode方法和decode方法是用于字符串编码和解码的,具体用法如下:
\1. encode方法
encode方法将Unicode字符串编码为另一种编码格式的字符串。它的语法如下:
str.encode(encoding="编码格式", errors="错误处理")
- encoding:要使用的编码格式。默认为"utf-8"。- errors:错误处理的方案。默认为"strict",如果存在无法编码的字符则会抛出UnicodeEncodeError异常。
例如:
s = "Hello, Python!" # 编码为“utf-8”格式 s_utf8 = s.encode(encoding="utf-8") print(s_utf8) # b'Hello, Python!'
\2. decode方法
decode方法将特定编码格式的字符串解码为Unicode字符串。它的语法如下:
bytes.decode(encoding="编码格式", errors="错误处理")
- encoding:要使用的编码格式。必须与编码时使用的格式一致。- errors:错误处理的方案。默认为"strict",如果存在无法解码的字符则会抛出UnicodeDecodeError异常。
例如:
s_utf8 = b'Hello, Python!' # 解码为Unicode字符串,默认使用“utf-8”格式 s1 = s_utf8.decode() print(s1) # Hello, Python!
2、字符串查找元素
Python 字符串中,字符串查找元素有以下几种方法:
\1. find()
方法:在字符串中查找给定的子字符串,并返回第一次出现的索引。如果没有找到子字符串,则返回 -1。
string = "hello world" index = string.find("world") print(index) # 输出 6
\2. index()
方法:与 find()
方法类似,也是在字符串中查找给定的子字符串,并返回第一次出现的索引。但如果没有找到子字符串,则会引发 ValueError
异常。
string = "hello world" index = string.index("world") print(index) # 输出 6
\3. rfind()
方法:与 find()
方法类似,但是它从字符串的末尾开始查找子字符串,并返回最后一次出现的索引。如果没有找到子字符串,则返回 -1。
string = "hello world" index = string.rfind("o") print(index) # 输出 7
\4. rindex()
方法:与 rfind()
方法类似,也是从字符串的末尾开始查找子字符串,并返回最后一次出现的索引。但如果没有找到子字符串,则会引发 ValueError
异常。
string = "hello world" index = string.rindex("o") print(index) # 输出 7
###
3、字符串大小写转换
\1. upper():将字符串中的小写字母转换为大写字母。
s = "hello, world!" s_upper = s.upper() # HELLO, WORLD!
\2. lower():将字符串中的大写字母转换为小写字母。
s = "HELLO, WORLD!" s_lower = s.lower() # hello, world!
\3. capitalize():将字符串的第一个字符大写,并将其余字符转换为小写。
s = "hello, world!" s_capitalize = s.capitalize() # Hello, world!
\4. title():将字符串中每个单词的第一个字符转换为大写,其余字符转换为小写
s = "hello, world!" s_title = s.title() # Hello, World!
4、拼接/分割字符串
1.join()
方法可以将字符串或可迭代对象中的元素连接起来,生成一个新的字符串。其基本语法为:连接符.join(可迭代对象)
。
例如:
seq = ['www', 'noob', 'com'] url = '.'.join(seq) print(url) # 输出www.noob.com
2.split()
方法是将一个字符串按照指定分隔符进行拆分,生成一个列表。其基本语法为:字符串.split(分隔符)
。
例如:
url = 'www.noob.com' lst = url.split('.') print(lst) # 输出 ['www', 'noob', 'com']
需要注意的是,括号中的分隔符是可选参数,若不指定分隔符,则默认按照空格分割。
5、删除字符串中特定字符
1.strip
是Python字符串方法之一,用来从字符串的开头和结尾移除指定字符(默认是空白字符)。比如:
string1 = " hello world " string2 = string1.strip() print(string1) # ' hello world ' print(string2) # 'hello world'
可以看到,strip
方法返回的是一个新字符串,移除了原字符串的开头和结尾的空白字符。
2.lstrip
和rstrip
是strip
方法的变体,lstrip只从左边移除,rstrip只从右边移除。比如:
string1 = "*$*$*$*$*$hello world*$*$*$*$*$" string2 = string1.lstrip("*$") # 移除左边的 * 和 $ string3 = string1.rstrip("*$") # 移除右边的 * 和 $ print(string1) # '*$*$*$*$*$hello world*$*$*$*$*$' print(string2) # 'hello world*$*$*$*$*$' print(string3) # '*$*$*$*$*$hello world'
6、统计字符串中元素出现的次数
Python字符串count方法用于统计一个字符串中某个字符或子字符串出现的次数。
语法格式如下:
str.count(sub, start= 0,end=len(string))
参数说明:- sub:指定检索的字符串。- start:可选参数,开始检索的位置,默认为0。- end:可选参数,结束检索位置,默认为字符串的长度。
方法返回值:
- 该方法返回字串出现的次数。
例如:统计字符串 s 中字母“o”的出现次数。
s = "Hello, how are you?" count = s.count("o") print(count) # 输出:3
7、字符串中元素替换
Python 字符串 replace() 方法可以将指定字符串中的一部分替换成新的字符串,语法如下:
str.replace(old, new[, max])
参数说明:
- old:表示被替换的旧字符串。- new:表示用来替换旧字符串的新字符串。- max:可选参数,表示替换次数,即最多替换出现的次数。
示例:
content = "Hello, World!" new_content = content.replace("World", "Python") print(new_content)
输出结果为:
Hello, Python!
8、字符串中元素对齐方式
Python中的字符串ljust,rjust和center方法用于返回一个指定长度的字符串,如果原字符串小于指定长度,则在左侧、右侧或两侧填充指定字符,使其达到指定长度。这些方法的语法如下:
- string.ljust(length, fillchar)
:返回一个指定长度的字符串,原字符串左对齐,右侧用指定字符填充。- string.rjust(length, fillchar)
:返回一个指定长度的字符串,原字符串右对齐,左侧用指定字符填充。- string.center(length, fillchar)
:返回一个指定长度的字符串,原字符串居中,两侧用指定字符填充。
其中,length
表示返回字符串的总长度,fillchar
表示填充字符,默认为空格。这些方法不会改变原字符串,而是返回一个新的字符串。
下面是一些使用示例:
>>> s = 'hello' >>> s.ljust(10, '*') 'hello*****' >>> s.rjust(10, '-') '-----hello' >>> s.center(10, '=') '==hello==='
需要注意的是,当指定长度小于等于字符串长度时,不会进行填充和居中操作,直接返回原字符串。
9、检查字符串以特定字符开头/结尾
1.startswith
方法用于检查字符串是否以给定的子字符串开头。它的基本语法是:
str.startswith(sub, start=0, end=len(string))
其中:- str
:要检查的字符串。- sub
:要检查的子字符串。- start
:起始位置,默认为 0
。- end
:结束位置,默认为字符串的长度。
示例:
str = "hello world" print(str.startswith("hello")) # True print(str.startswith("world")) # False
2.endswith
方法用于检查字符串是否以给定的子字符串结尾。它的基本语法是:
str.endswith(suffix, start=0, end=len(string))
其中:- str
:要检查的字符串。- suffix
:要检查的后缀子字符串。- start
:起始位置,默认为 0
。- end
:结束位置,默认为字符串的长度。
示例:
str = "hello world" print(str.endswith("world")) # True print(str.endswith("hello")) # False
10、检查字符串中元素大小写
1.isupper()
方法用于检查字符串中的所有字母是否为大写字母,如果是则返回True
,否则返回False
。
str1 = "HELLO WORLD" print(str1.isupper()) # True str2 = "Hello World" print(str2.isupper()) # False
2.islower()
方法用于检查字符串中的所有字母是否为小写字母,如果是则返回True
,否则返回False
。
str1 = "hello world" print(str1.islower()) # True str2 = "Hello World" print(str2.islower()) # False
需要注意的是,这两个方法只会判断字符串中的字母是否全为大写或小写,如果字符串中有其他字符,比如数字或标点符号等,则不会影响结果。
11、检查字符串中元素是字母/数字
1.- isalpha():如果所有字符都是字母,则返回True,否则返回False。
示例代码:
string1 = 'Hello' string2 = 'Hello123' print(string1.isalpha()) # True print(string2.isalpha()) # False
2.- isdigit():如果所有字符都是数字,则返回True,否则返回False。
示例代码:
string1 = '123' string2 = '12.3' print(string1.isdigit()) # True print(string2.isdigit()) # False