1、字符串的表示方法

  • (1)字符串可以使用单引号,双引号,三个单引号,单个双引号表示
>>> "hello world"
'hello world'
>>> 'hello world'
'hello world'
>>> """hello world
... hello world
... hello world
... """
'hello world\nhello world\nhello world\n'
>>> '''hello world
... hello world
... hello world
... '''
'hello world\nhello world\nhello world\n'
  • (2)字符串中若有双引号,可以采用单引号嵌套双引号的方式,也可以采用后面要讲的转义的部分
>>> 'he said:"hello world"'
'he said:"hello world"'

2、转义字符

  • (1)常用的转义字符
\n   换行
\\   \
\t   制表符
\"   "
\'   '
  • (2)字符串中使用转义举例
>>> print("hello \\n world")
hello \n world
>>> print("hello \"Tom\"")
hello "Tom"
>>> print("hello\tworld")
hello   world
>>> print("hello\nworld")
hello
world
  • (3)在Windows操作系统上使用文件路径时要特别小心,注意使用转义符对\进行转义
>>> print("C:\north\nrothwest")
C:
orth
rothwest
>>> print("C:\\north\\northwest")
C:\north\northwest
>>> print(r"C:\north\northwest")
C:\north\northwest
>>>

3、字符串的常用运算

  • (1)字符串可以用加号来拼接字符串,使用*号来重复字符串
>>> "hello" "world"
'helloworld'
>>> "hello"*3
'hellohellohello'
  • (2)字符串可以通过下标获取具体的字符,下标从0开始,下标不允许超过边界
>>> a="hello world"
>>> print(a[0])
h
>>> print(a[2])
l
>>> print(a[-1])
d
>>> print(a[-3])
r
>>> print(a[11])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
  • (3)字符串可以通过切片获取字符串的片段,坚持前闭后开的原则
>>> a="hello world"
>>> print(a[0:4])
hell
>>> print(a[1:3])
el
>>> print(a[0:-1])
hello worl
>>> print(a[0:10])
hello worl
  • (4)字符串中切片操作,右边界值允许炒作最大值,超过后表示取到最右边的字符
>>> print(a[0:11])
hello world
  • (5)字符串切片操作可以使用三个参数,第三个参数表示步长
>>> print(a[1:9:3])
eoo
  • (6)字符串切片操作的参数可以省略,省略第一个参数表示左侧从头开始取,省略第二参数,表示右侧到字符串末尾
>>> print(a[:3])
hel
>>> print(a[3:])
lo world
>>> print(a[::3])
hlwl
  • (7)字符串切片操作的参数中若第一个参数大于等于第二个参数,且第二个参数不为负数时,表示取出来的子串为空串
>>> print(a[5:1])
>>> 
>>> print(a[10:0])
>>> 
  • (8)字符串可以通过in或者not in判断字符或者字符串是否在字符串中
>>> 'h' in "hello world"
True
>>> 'z' in "hello world"
False
>>> 'z' not in "hello world"
True
  • (9)通过len函数计算字符串的长度
>>> len("hello world")
11
  • (10)通过max和min计算字符串中的最小和最大的值
>>> max("hello world")
'w'
>>> min("hello world")
' '
  • (11)ord可以将字符转换为整数,chr可以将整数转换为字符
>>> ord('a')
97
>>> chr(90)
'Z'

4、字符串常用的函数

  • (1)capitalize() 将字符串首字母大写,其他字母变成小写
>>> a="hello Word HeLLO WORd"
>>> a.capitalize()
'Hello word hello word'
  • (2)lower() 将大写字母转换为小写字母(仅限ASCII编码范围内的语言)
>>> a="HEllo WorLD HelLO WoRLD"
>>> a.lower()
'hello world hello world'
  • (3)casefold() 将大写字母转换为小写字母(ASCII编码范围外的语言也支持)
>>> a="HEllo WorLD HelLO WoRLD"
>>> a.casefold()
'hello world hello world'
>>> a="ß"   # 德语
>>> a
'ß'
>>> a.casefold()
'ss'
>>> a.lower()
'ß'
  • (4)upper() 将小写字母转换为大写字母(仅限ASCII编码范围内的语言)
>>> a="hello Word HeLLO WORd"
>>> a.upper()
'HELLO WORD HELLO WORD'
  • (5)swapcase() 将小写字母转换为大写字母,将原来大写的变为小写字母
>>> a="HEllo WorLD HelLO WoRLD"
>>> a.swapcase()
'heLLO wORld hELlo wOrld'
  • (6)title() 将字符串中每个单词的首字母大写
>>> a="HEllo WorLD HelLO WoRLD"
>>> a.title()
'Hello World Hello World'
  • (7)strip(chars=None) 如果chars不填,则去除字符串两端的空格,如果chars指定了字符,则去除字符串两端的chars指定的字符
>>> a="   hello world    "
>>> a.strip()
'hello world'
>>> a="hahahahello world hello world hahahaha"
>>> a.strip("ha")
'ello world hello world '
>>> a="hahahahaahello world hahahaha"
>>> a.strip("ha")
'ello world '
>>> a="hello world gogole world hello"
>>> a.strip("olhe")
' world gogole world '
  • (8)lstrip(chars=None),和strip功能类似,只不过lstrip只去除字符串左边空格或者chars指定的字符
>>> a="  hello world   "
>>> a.lstrip()
'hello world   '
>>> a="hello world hello"
>>> a.lstrip("elho")
' world hello'
  • (9)rstrip(chars=None),和strip功能类似,只不过rstrip只去除字符串右边空格或者chars指定的字符
>>> a=" hello world "
>>> a.rstrip()
' hello world'
>>> a="hello world hello"
>>> a.rstrip("elho")
'hello world '
  • (10)rjust(width,fillchar=’ ‘),返回一个原字符串右对齐,并使用fillchar指定的字符填充至width长度的字符串,fillchar不指定时默认为空格
>>> a="hello world"
>>> a.rjust(20)
'         hello world'
>>> a.rjust(20,'x')
'xxxxxxxxxhello world'
  • (11)ljust(width,fillchar=’ ‘),返回一个原字符串左对齐,并使用fillchar指定的字符填充至width长度的字符串,fillchar不指定时默认为空格
>>> a="hello world"
>>> a.ljust(20)
'hello world         '
>>> a.ljust(20,'x')
'hello worldxxxxxxxxx'
  • (12)center(width,fillchar=’ ‘),返回一个原字符串居中对齐,并使用fillchar指定的字符填充到width长度的字符串,fillchar不指定时默认为空格
>>> a="hello world"
>>> a.center(20)
'    hello world     '
>>> a="hello world"
>>> a.center(20,'x')
'xxxxhello worldxxxxx'
  • (13)count(sub,start=0,end=len(string)),返回字符串包含子串的数量,可以指定查询的起始位置和结束位置,不指定则默认为整个字符串中计数
>>> a="hello world"
>>> a.count('l')
3
>>> a.count('l',1,5)
2
>>> a="hello world hello world hello"
>>> a.count("hello")
3
  • (14)index(sub,start=0,end=len(string)),返回字符串中查找到的第一个子串的起始位置索引值,可以指定查找起始和结束范围,若查找不到则报ValueError的异常
>>> a="hello world"
>>> a.index('h')
0
>>> a.index('x')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> a.index('l',5,20)
9
>>> a="hello world hello world"
>>> a.index("world")
  • (15)rindex(sub,start=0,end=len(string)) 返回字符串中查找到的最后一个子串的起始位置的索引值,可以指定查找起始和结束范围,若查找不到则报ValueError的异常
>>> a="hello world"
>>> a.rindex("l")
9
>>> a.rindex("l",0,5)
3
>>> a="hello world hello world hello"
>>> a.rindex("world")
18
  • (16)find(sub,start=0,end=len(string)) 返回字符串中查找到的第一个子串的起始位置索引值,可以指定查找起始和结束范围,若查找不到则返回-1
>>> a="hello world"
>>> a.find('l')
2
>>> a.find('x')
-1
>>> a.find('l',6,10)
9
>>> a="hello world hello world"
>>> a.find("world")
6
  • (17)rfind(sub,start=0,end=len(string)) 返回字符串中查找到最后一个子串的起始位置索引,可以指定查找起始和结束范围,若查找不到则返回-1
>>> a="hello world"
>>> a.rfind('l')
9
>>> a.rfind('x')
-1
>>> a.rfind('l',1,6)
3
  • (18)split(rep=None,maxsplit=-1) 将字符串根据sep分割,如果sep不填则默认使用空格分割,如果maxsplt不指定则默认将根据字符串中所有的sep分割,否则分割指定的数目
>>> a="hello world hello world hello world"
>>> a.split()
['hello', 'world', 'hello', 'world', 'hello', 'world']
>>> a.split(" ",2)
['hello', 'world', 'hello world hello world']
>>> a.split("world")
['hello ', ' hello ', ' hello ', '']
>>> a.split('x')
['hello world hello world hello world']
  • (19)split(rep=None,maxsplit=-1) 将字符串从右侧开始根据sep分割,如果sep不填则默认使用空格分割,如果maxsplt不指定则默认将根据字符串中所有的sep分割,否则分割指定的数目
>>> a="hello world hello world hello world"
>>> a.rsplit()
['hello', 'world', 'hello', 'world', 'hello', 'world']
>>> a.rsplit(" ")
['hello', 'world', 'hello', 'world', 'hello', 'world']
>>> a.rsplit(" ",2)
['hello world hello world', 'hello', 'world']
>>> a.rsplit("world")
['hello ', ' hello ', ' hello ', '']
  • (20)splitlines(keepends=False) 按照换行符(\r,\r\n,\n)分割,如果keepends不填默认为False,则返回的每一行没有回车符,如果keepends设置为True则每一行带有换行符
>>> a="hello world 01\n hello world 02\r hello world 03 \r\n hello world 04"
>>> a
'hello world 01\n hello world 02\r hello world 03 \r\n hello world 04'
>>> a.splitlines()
['hello world 01', ' hello world 02', ' hello world 03 ', ' hello world 04']
>>> a.splitlines(True)
['hello world 01\n', ' hello world 02\r', ' hello world 03 \r\n', ' hello world 04']
  • (21)partition(sep) 根据指定的sep将字符串分割,返回一个三元组,第一个元素为分割符左边的部门,第二个元素为分隔符本身,第三个元素为分隔符有点的部分,若字符串中没有找到分隔符sep,则返回一个三元组,第一个元素为字符串本身,第二个第三个为空字符串
>>> a="hello world hello world"
>>> a.partition(" ")
('hello', ' ', 'world hello world')
>>> a.partition('x')
('hello world hello world', '', '')
  • (22)rpartition(sep) 根据指定的sep将字符串从右侧开始查找并分割,返回一个三元组,第一个元素为分割符左边的部门,第二个元素为分隔符本身,第三个元素为分隔符有点的部分,若字符串中没有找到分隔符sep,则返回一个三元组,第一个元素为字符串本身,第二个第三个为空字符串
a="hello world hello world"
>>> a.rpartition(" ")
('hello world hello', ' ', 'world')
  • (23)replace(old,new,count=-1) 将字符串中的old替换为new,如果不指定count则全部替换,否则按照count指定的数目替换
>>> a="hello world hello world hello world"
>>> a.replace("hello","Hello")
'Hello world Hello world Hello world'
>>> a.replace("hello","Hello",1)
'Hello world hello world hello world'
  • (24)zfill(width) 将字符串用0填充至width指定的长度,若指定的长度比字符串长度还小,则不作任何操作
>>> a="hello world"
>>> a.zfill(20)
'000000000hello world'
>>> a.zfill(4)
'hello world'
  • (25)join(iterable) 将列表中的元素以指定的字符连接为新的字符串
>>> a=["hello","world","hello","world","hello","world"]
>>> " ".join(a)
'hello world hello world hello world'
>>> 'x'.join(a)
'helloxworldxhelloxworldxhelloxworld'
>>> '\n'.join(a)
'hello\nworld\nhello\nworld\nhello\nworld'
  • (26)format() 字符串格式化

    • format使用位置对字符串进行字符串进行变量替换
    >>> "{} {}".format("hello","world")
    'hello world'
    >>> "{0} {1}".format("hello","world")
    'hello world'
    >>> "{1} {0} {1}".format("hello","world")
    'world hello world'
    • 2)使用参数指定对字符串进行变量替换
    >>> "{v1} {v2}".format(v1="hello",v2="world")
    'hello world'
    >>> "{v1} this is a string {v2}".format(v2="world",v1="hello")
    'hello this is a string world'
    • 3)数字格式化
    >>> a=3.141592653
    >>> "{:.2f}".format(a)
    '3.14'
    >>> "{: .2f}".format(a)
    ' 3.14'
    >>> "{:.0f}".format(a)
    '3'
    >>> a=1000000000
    >>> "{:0>12d}".format(a)
    '001000000000'
    >>> "{:x<12d}".format(a)
    '1000000000xx'
    >>> "{:,}".format(a)
    '1,000,000,000'
    >>> "{:.2e}".format(a)
    '1.00e 09'
    >>> "{:>15d}".format(a)
    '     1000000000'
    >>> "{:<15d}".format(a)
    '1000000000     '
    >>> "{:^15d}".format(a)
    '  1000000000   '
    >>> "{:.2%}".format(0.25)
    '25.00%'
    >>> '{:b}'.format(11)
    '1011'
    >>> '{:d}'.format(11)
    '11'
    >>> '{:o}'.format(11)
    '13'
    >>> '{:x}'.format(11)
    'b'
    >>> '{:#x}'.format(11)
    '0xb'
    >>> '{:#X}'.format(11)
    '0XB'
  • (27)format_map() 使用字典格式的数据对字符串进行变量替换
>>> info={"v1":"hello","v2":"world"}
>>> "{v1} {v2}".format_map(info)
'hello world'
  • (28)encode(encoding=”utf-8”,errors=’strict’) 以指定的编码格式编码字符串,默认的是utf-8,errors指定不同的错误处理方案
    strict意为编码错误引起一个UnicodeError,其他可选的值有: ‘ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ 以及通过 codecs.register_error() 注册的任何值
>>> "hello world".encode("utf-8")
b'hello world'
>>> "hello world".encode("gbk")
b'hello world'
>>> "hello world".encode("ascii")
b'hello world'
>>> "你好,世界!".encode("utf-8")
b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x81'
>>> "你好,世界!".encode("gbk")
b'\xc4\xe3\xba\xc3\xa3\xac\xca\xc0\xbd\xe7\xa3\xa1'
>>> "你好,世界!".encode("ascii")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)
>>> "你好,世界!".encode("ascii","ignore")
b''
  • (29)maketrans() 创建字符映射的转换表,可以是一个参数,一个参数是时必须为字典dict,返回的类型为dict,key和value均用Unicode编码表示,也可以接受两个参数,如果是两个参数,则两个参数的类型为字符串str类型,并且两个参数的额字符串长度相同,以此来建立对应位置的映射关系
>>> str.maketrans({"a":1,"b":2,"c":3})
{97: 1, 98: 2, 99: 3}
>>> str.maketrans("hello","world")
{104: 119, 101: 111, 108: 108, 111: 100}
  • (30)translate(table) 根据maketrans生成的映射表对字符串进行字符替换,如果转换表中字符对应的value值为None的,则在此字符串中删除此字符
>>> table=str.maketrans("hello","world")
>>> "hello world hello world".translate(table)
'wolld wdrld wolld wdrld'
>>> table=str.maketrans({"h":"w","e":None,"l":"o","o":None})
>>> "hello world".translate(table)
'woo wrod'
  • (31)expandtabs(tabsize=8) 吧字符串中的tab字符\t转换为指定数量的空格,默认为8个
>>> "hello\tworld".expandtabs(tabsize=8)
'hello   world'
>>> "hello\tworld".expandtabs(tabsize=4)
'hello   world'
>>> "hello\tworld".expandtabs(tabsize=16)
'hello           world'
  • (32)startswith(prefix,start=0,end=len(string)) 判断字符串是否已给定的prefix为起始,如果是返回True,否则返回False,同时可以指定判断起始的位置。start和end默认为0和字符串的长度.
    prefix还可以是一个有字符串元素组成的元组,只要有一个匹配上,即返回True,否则返回False
>>> a="hello world"
>>> a.startswith("h")
True
>>> a.startswith("hello")
True
>>> a.startswith(" ",5,10)
True
>>> a.startswith(" ",3,10)
False
>>> a.startswith(("haha","hehe","h","w"))
True
>>> a.startswith(("haha","hehe","m","w"))
False
  • (33)endswith(suffix,start=0,end=len(string)) 判断字符串是否已给定的suffix为结尾,如果是返回True,否则返回False,同时可以指定判断起始的位置。start和end默认为0和字符串的长度.
    suffix还可以是一个有字符串元素组成的元组,只要有一个匹配上,即返回True,否则返回False
>>> a="hello world"
>>> a.endswith("d")
True
>>> a.endswith("world")
True
>>> a.endswith("d",0,4)
False
>>> a.endswith(("hello","heheh","word","wd","d"))
True
>>> a.endswith(("hello","heheh","word","wd","h"))
False
  • (34)isupper() 如果字符串的所有字符都是大写,则返回True,否则返回False
>>> "HELLO".isupper()
True
>>> "HeLLO".isupper()
False
>>> "HELLO WORLD".isupper()
True
>>> " ".isupper()
False
  • (35)islower() 如果字符串的所有字符都是小写,则返回True,否则返回False
>>> "hello world".islower()
True
>>> "Hello world".islower()
False
>>> " ".islower()
False
  • (36)istitle() 判断字符串中是否每个单词的首字母都睡大写,如果是返回True,否则返回False
>>> "Hello World".istitle()
True
>>> "Hello world".istitle()
False
  • (37)isspace() 如果字符串中的所有的字符都是空格,并且至少有一个字符,则返回True,否则返回False
>>> "".isspace()
False
>>> " ".isspace()
True
>>> "    ".isspace()
True
>>> "\t".isspace()
True
>>> "\n".isspace()
True
  • (38)isprintable() 如果字符串中所有字符都可打印返回True,否则返回False
>>> "hello ".isprintable()
True
>>> " ".isprintable()
True
>>> "".isprintable()
True
>>> "\t".isprintable()
False
>>> "\n".isprintable()
False
>>> "\r".isprintable()
False
>>> "hello\nworld".isprintable()
False
  • (39)isnumeric() 如果字符串中所有字符均有数字组成,返回True,否则返回False
>>> "hello".isnumeric()
False
>>> "1234567890".isnumeric()
True
>>> "0123".isnumeric()
True
>>> " 0234 ".isnumeric()
False
>>> "".isnumeric()
False
  • (40)isidentifier() 判断字符串是否为python的有效的标识符,python有效的额标识符为字母或下划线开头,由数字字母和下划线组成的
>>> "hello".isidentifier()
True
>>> "def".isidentifier()
True
>>> "1abc".isidentifier()
False
>>> "class".isidentifier()
True
>>> "a-b".isidentifier()
False
  • (41)isdigit() 如果字符串中所有字符均有数字组成,返回True,否则返回False
>>> "123".isdigit()
True
>>> "a12".isdigit()
False
>>> "0123".isdigit()
True
>>> "".isdigit()
False
  • (42)isdecimal() 如果字符串中所有字符均有十进制字符组成,返回True,否则返回False
>>> "0123456789".isdecimal()
True
>>> "0b11".isdecimal()
False
>>> "a0".isdecimal()
False
  • (43)isascii() 如果字符串中所有字符均为ascii范围内编码,则返回True,否则返回False
>>> "hello world".isascii()
True
>>> "你好".isascii()
False
  • (44)isalpha() 如果字符串中至少有一个字符并且所有字符都是字母,则返回True,否则返回False
>>> "hello world".isalpha()
False
>>> "helloworld".isalpha()
True
>>> "abc123".isalpha()
False
  • (45)isalnum() 如果字符串中每个字符都是由字母或者数字组成,则返回True,否则返回False
>>> "hello world".isalnum()
False
>>> "helloworld".isalnum()
True
>>> "abc123".isalnum()
True
最后修改:2022 年 05 月 11 日
如果觉得我的文章对你有用,请随意赞赏