Python – 字符串常用函数详解
前言
字符串是编程中最重要的数据类型,也是最常见的
字符串的表示方式
- 单引号 ‘ ‘
- 双引号 ” “
- 多引号 “”” “””” 、 ”’ ”’
print("hello world") print('hello world') print("""hello world""") # 输出结果 hello world hello world hello world
为什么需要单引号,又需要双引号
因为可以在单引号中包含双引号,或者在双引号中包含单引号
# 单双引号 print("hello 'poloyy' world") print('this is my name "poloyy"') # 输出结果 hello 'poloyy' world this is my name "poloyy"
多行字符串
正常情况下,单引号和双引号的字符串是不支持直接在符号间换行输入的,如果有需要可以用多引号哦!
# 多行字符串 print(""" hello world """) print(""" this is my name poloyy """) # 输出结果 hello world this is my name poloyy
转义符
在字符前加 \ 就行
常见的有
- \n:换行
- \t:缩进
- \r:回车
栗子
比如在字符串双引号间还有一个双引号,就需要用转义符
# 转义符 print("hello \"poloyy\" world") print('my name is \'poloyy\'') # 输出结果 hello "poloyy" world my name is 'poloyy'
假设 \ 只想当普通字符处理呢?
print("反斜杠 \\ 是什么") print("换行符是什么 \\n") # 输出结果 反斜杠 \ 是什么 换行符是什么 \n
window 路径的栗子
print("c:\nothing\rtype") print("c:\\nothing\\rtype") # 输出结果 c:\nothing\ c: type c:\nothing\rtype
更简洁的解决方法
用转义符会导致可读性、维护性变差,Python 提供了一个更好的解决方法:在字符串前加 r
print(r"c:\nothing\rtype") # 输出结果 c:\nothing\rtype
关于更多 r”” 的讲解下面:Python – r”, b”, u”, f” 的含义
字符串运算:+ 运算
直接拼接的作用
# + 运算 print("123" + "123") print("123" + "abc") print("123", "456") # 输出结果 123123 123abc 123 456
字符串运算:下标和切片
获取字符串中某个字符
字符串是一个序列,所以可以通过下标来获取某个字符
# 获取字符串某个字符 str = "hello world" print(str[0]) print(str[1]) print(str[6]) print(str[-1]) print(str[-5]) # 输出结果 h e w d l
如果是负数,那么是倒数,比如 -1 就是倒数第一个元素,-5 就是倒数第五个元素
获取字符串中一段字符
Python 中,可以直接通过切片的方式取一段字符
切片的语法格式
str[start : end : step]
- 获取列表 列表 中在 [start, end) 范围的子字符串
- start:闭区间,包含该下标的字符,第一个字符是 0
- end:开区间,不包含该下标的字符
- step:步长,设为 n,则每隔 n 个元素获取一次
栗子
print("hello world'[:] ", 'hello world'[:]) # 取全部字符 print("hello world'[0:] ", 'hello world'[0:]) # 取全部字符 print("hello world'[6:] ", 'hello world'[6:]) # 取第 7 个字符到最后一个字符 print("hello world'[-5:] ", 'hello world'[-5:]) # 取倒数第 5 个字符到最后一个字符 print("hello world'[0:5] ", 'hello world'[0:5]) # 取第 1 个字符到第 5 个字符 print("hello world'[0:-5] ", 'hello world'[0:-5]) # 取第 1 个字符直到倒数第 6 个字符 print("hello world'[6:10] ", 'hello world'[6:10]) # 取第 7 个字符到第 10 个字符 print("hello world'[6:-1] ", 'hello world'[6:-1]) # 取第 7 个字符到倒数第 2 个字符 print("hello world'[-5:-1] ", 'hello world'[-5:-1]) # 取倒数第 5 个字符到倒数第 2 个字符 print("hello world'[::-1] ", 'hello world'[::-1]) # 倒序取所有字符 print("hello world'[::2] ", 'hello world'[::2]) # 步长=2,每两个字符取一次 print("hello world'[1:7:2] ", 'hello world'[1:7:2]) # 步长=2,取第 2 个字符到第 7 个字符,每两个字符取一次 # 输出结果 hello world'[:] hello world hello world'[0:] hello world hello world'[6:] world hello world'[-5:] world hello world'[0:5] hello hello world'[0:-5] hello hello world'[6:10] worl hello world'[6:-1] worl hello world'[-5:-1] worl hello world'[::-1] dlrow olleh hello world'[::2] hlowrd hello world'[1:7:2] el
获取字符串长度
print(len("123")) # 输出结果 3
字符串的函数
Python 提供了很多内置的字符串函数,具体下面:
Python – 字符串常用函数详解
str.index(sub, start=None, end=None)
作用:查看sub是否在字符串中,在的话返回索引,且只返回第一次匹配到的索引;若找不到则报错;可以指定统计的范围,[start,end) 左闭区间右开区间
str = "helloworldhhh" print(str.index("h")) print(str.index("hhh")) # print(str.index("test")) 直接报语法错误:ValueError: substring not found
执行结果
0 10
str.find(sub, start=None, end=None)
作用:和index()一样,只是找不到不会报错,而是返回-1
str = "helloworldhhh" print(str.find("h")) print(str.find("hhh")) print(str.find("test"))
执行结果
0 10 -1
str.count( sub, start=None, end=None)
作用:统计子字符串的数量;可以指定统计的范围,[start,end) 左闭区间右开区间
str = "hello world !!! hhh" print(str.count(" ")) print(str.count(" ", 5, 10))
执行结果
3 1
str.split(str=””, num=string.count(str))
作用:将字符串按照str分割成列表,如果参数 num 有指定值,则分隔 num+1 个子字符串
str = "hello world !!! hhh" print(str.split(" ")) print(str.split(" ", 1))
执行结果
['hello', 'world', '!!!', 'hhh'] ['hello', 'world !!! hhh']
str.strip(chars = ” “)
作用:移除字符串头尾指定的字符序列chars,默认为空格
str.lstrip(chars = ” “)
作用:移除字符串头部指定的字符序列chars,默认为空格
str.rstrip(chars = ” “)
作用:移除字符串尾部指定的字符序列chars,默认为空格
str = " hello every " print("1", str.strip(), "1") print(str.lstrip(), "1") print("1", str.rstrip()) str = "!!! cool !!!" print(str.strip("!"))
执行结果
1 hello every 1 hello every 1 1 hello every cool
str.replace(old,new,count= -1)
作用:把字符串中的 old(旧字符串) 替换成 new(新字符串),count代表最多替换多少次,默认-1代表全部替换
str = "hello world !!! hhh" print(str.replace(" ", "-")) print(str.replace(" ", "-", 1))
执行结果
hello-world-!!!-hhh hello-world !!! hhh
str.join(sequence)
作用:将序列中的元素以指定的字符连接生成一个新的字符串
lists = ["1", "2", "3"] tuples = ("1", "2", "3") print("".join(lists)) print("".join(tuples)) print("-".join(lists))
执行结果
123123 1-2-3
知识点
- “”.join(lists) 这是最常见的将列表、元组转成字符串的写法
- 列表里面只能存放字符串元素,有其他类型的元素会报错
- 元组也能传进去
str.upper()
作用:将字符串都变成大写字母
str.lower()
作用:将字符串都变成小写字母
str = "hello world !!! hhh" print(str.upper()) print(str.lower())
执行结果
HELLO WORLD !!! HHH hello world !!! hhh
str.startswith(prefix, start=None, end=None)
作用:检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False;可以指定统计的范围,[start,end) 左闭区间右开区间
str.endswith(self, suffix, start=None, end=None)
作用:相反这是结尾
str = "hello world !!! hhh" print(str.startswith("h")) print(str.startswith("hh")) print(str.endswith("h")) print(str.endswith("hhhh"))
执行结果
True False True False
str.isdigit()
作用:检查字符串是否只由数字组成
str = "123134123" print(str.isdigit())
执行结果
true
str.isalpha()
作用:检查字符串是否只由字母组成
str = "abc" print(str.isalpha())
执行结果
true
str.splitlines([keepends])
作用:将字符串按照行 (‘\r’, ‘\r\n’, \n’) 分隔
str = """ 123 456 789 """ print(str.splitlines()) with open("./file1.txt", encoding="utf-8") as f: lists = f.read().splitlines() print(lists)
执行结果
['', '123', '456', '789'] ['name: Jack ; salary: 12000', ' name :Mike ; salary: 12300', 'name: Luk ; salary: 10030', ' name :Tim ; salary: 9000', 'name: John ; salary: 12000', 'name: Lisa ; salary: 11000']
Python 字符串格式化的两种方式
- %
- format
- 其实还有第三种 f””
%,关于整数的输出
- %o:oct 八进制
- %d:dec 十进制
- %x:hex 十六进制
print("整数:%d,%d,%d" % (1, 22.22, 33)) print("整数不足5位,左边补空格 %5d " % 22) print("整数不足5位,左边补0 %05d " % 22) print("整数不足5位,右边补空格 %-5d " % 22, "end") print("八进制 %o" % 222) print("十六进制 %x" % 12)
执行结果
整数:1,22,33 整数不足5位,左边补空格 22 整数不足5位,左边补0 00022 整数不足5位,右边补空格 22 end 八进制 336 十六进制 c
包含知识点
- 当你有多个参数需要格式化输出的时候,需要用元组 (1,2,3) ;注意不能用列表因为列表是可变的
- 若传入的是浮点数如 22.55 ,最后输出的是22,不会四舍五入哦
- 若传入了字符串 ’22’ ,是会报错滴!
%,关于浮点数的输出
print("浮点数:%f,%f " % (1, 22.22)) print("浮点数保留两位小数:%.2f " % 22.222) print("浮点数保留两位小数,宽5位,不足补0:%05.5f " % 2.222)
执行结果
浮点数:1.000000,22.220000 浮点数保留两位小数:22.22 浮点数保留两位小数,宽5位,不足补0:02.22
包含知识点
默认保留6位小数,可通过 .2f 这种形式指定小数位,2代表保留两位
%,关于字符串的输出
print("字符串:%s,%s,%s" % (1, 22.22, [1, 2])) print("字符串不足5位,左边补空格 %5s " % '2') print("字符串不足5位,右边补空格 %-5s " % '2', "end") print("字符串宽10位,截取两位 %10.2s " % "hello.world")
执行结果
字符串:1,22.22,[1, 2] 字符串不足5位,左边补空格 2 字符串不足5位,右边补空格 2 end 字符串宽10位,截取两位 he
包含知识点
- 可以传入任意类型的数据,譬如整数、浮点数、列表、元组甚至字典,他都会自动转成字符串类型
format格式化输出
相对基本格式化输出采用 % 的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号 {} 作为特殊字符代替 %
format,位置匹配(最常用)
- 不带编号,即“{}”
- 带数字编号,可调换顺序,即“{1}”、“{2}”
- 带关键字,即“{a}”、“{tom}”
print("今天是{}的{}生日会".format("帅哥", 18)) print("今天是{1}的{0}生日会".format("帅哥", 18)) print("今天是{0}的{1}生日会".format("帅哥", 18)) print("今天是{name}的{key}生日会".format(22, 11, name="帅哥", key=18)) print("今天是{name}的{key}生日会,接着上{}".format("test", name="帅哥", key=18)) # 以下会报错 print("今天是{0}的{}生日会".format("帅哥", 18)) print("今天是{name}的{key}生日会,接着上{}".format( name="帅哥", key=18,"test"))
执行结果
今天是帅哥的18生日会 今天是18的帅哥生日会 今天是帅哥的18生日会 今天是帅哥的18生日会今天是帅哥的19生日会,接着上test
包含知识点
- 当你只写了 {} 时,默认按传入的值的顺序读取
- 当你写了数字编号 {1} ,则可以读取对应位置上的值,从0开始
- 当你指定了关键字 {name} ,如果不指定 name=xxx ,则会报错
- 当你指定了关键字,又只写了 {} 时,你传入带有关键字指定的值必须写在后面,类似函数(形参在前,实参在后)
- {} 和 {1} 是不能共存的
总结
当用到format时,一个字符串里面的格式化输出只用一种方式,不要混合使用,容易出问题且没有必要
format,指定数据类型输出
print("整数{:d}".format(123)) print("浮点数{:5.2f}".format(123.19)) print("字符串{:s}".format('123')) print("八进制{:o}".format(12)) print("十六进制{:x}".format(13))
执行结果
整数123 浮点数123.19 字符串123 八进制14 十六进制d
包含知识点
- 指定了 :s ,则只能传字符串值,如果传其他类型值不会自动转换
- 当你不指定类型时,你传任何类型都能成功,如无特殊必要,可以不用指定类型
- 如果要结合数字编号和关键字使用可以如下
print("关键字 {num:d}".format(num=123)) print("数字编号 {0:d},{1:s}".format(123, "123"))
执行结果
关键字 123 数字编号 123,123
format,位数补齐
print('默认左对齐,宽度为10,不足补空格:{:10}'.format("123"), "end") print('左对齐,宽度为10,不足补空格:{:<10}'.format("123"), "end") print('右对齐,宽度为10,不足补空格:{}{:>10}'.format("start", "123"))print('右对齐,宽度为10,取两位小数,不足补0:{:0>10.2f}'.format(22.22555))
执行结果
默认左对齐,宽度为10,不足补空格:123 end 左对齐,宽度为10,不足补空格:123 end 右对齐,宽度为10,不足补空格:start 123 右对齐,宽度为10,取两位小数,不足补0:0000022.23
包含知识点
- 默认左对齐可以不用就加 <
- 当你不指定数据类型时,传什么类型的值都能成功格式化输出
format,拓展使用
print("总是显示符号:{:0>+8.2f},{:0>+8.2f}".format(3.14, -3.14)) print("百分数:{:%} {:.2%}".format(3 / 7, 3 / 7)) print("逗号分隔,一般用在金钱 {:,}".format(12345678)
执行结果
总是显示符号:000+3.14,000-3.14 百分数:42.857143% 42.86% 逗号分隔,一般用在金钱 12,345,678
包含知识点
- + 的意义在于,当我们输出的是正数也能看到符号
- 百分数是真的百分数,不是单单加个 % ;譬如0.25667,变成百分数就是 25.67%
-
, 固定隔三位数字;传入字符串会报错哦
字符串前加 f(重点!敲黑板!)
作用:相当于 format() 函数
name = "帅哥" age = 12 print(f"my name is {name},age is {age}")
执行结果
my name is 帅哥,age is 12
字符串前加 r
r”” 的作用是:去除转义字符
场景:想复制某个文件夹的目录,假设是 F:\Python_Easy\n4\test.py
当你不用 r”” ,你有三种写法
print("F:\Python_Easy\n4\test.py ") print("F:\\Python_Easy\\n4\\test.py ") print("F:/Python_Easy/n4/test.py ")
而通常如果直接复制目录路径的话,你就粘贴出来的字符串就是第一行代码所示,所有 \ 会当成转义符;而为了消除转义作用,需要手动再加一个 \ ,否则你也得手动改成第三行代码一样
执行结果
F:\Python_Easy 4 est.py F:\Python_Easy\n4\test.py F:/Python_Easy/n4/test.py
而 r”” 的出现就是为了避免这种情况,如下:
print(r"F:\Python_Easy\n4\test.py ")
执行结果
F:\Python_Easy\n4\test.py
字符串前加 b
b” “的作用是:使后面字符串是bytes 类型
print("中文".encode(encoding="utf-8")) print(b'\xe4\xb8\xad\xe6\x96\x87'.decode()) print(r'\xe4\xb8\xad\xe6\x96\x87')
执行结果
b'\xe4\xb8\xad\xe6\x96\x87' 中文 \xe4\xb8\xad\xe6\x96\x87
可以看到,当你不加 b”” 时,他也就是个普通的字符串而已,不会识别为字节类型
bytes应用场景:像图片、音视频等文件的读写就是用bytes数据
字符串前加 u
作用:后面字符串以 Unicode 格式 进行编码
实际场景:一般用在中文字符串前面,防止因为源码储存格式问题,导致再次使用时出现乱码。
建议所有编码方式采用utf8
Python – bytes与字符串的相互转化
decode和encode的区别和介绍
str.decode(encoding='UTF-8',errors='strict')
str.encode(encoding='UTF-8',errors='strict')
- 显而易见decode是解码,encode是编码
- 解码代表bytes类型转成str类型
- 编码代表str类型转成bytes类型
- 而bytes类型的数据一般在写入文件时需要用到
直接上代码
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 """ 5 __title__ = 6 __Time__ = 2020/2/21 15:56 7 8 """ 9 # bytes转字符串方式一 10 b = b'\xe9\x80\x86\xe7\x81\xab' 11 string = str(b, 'utf-8') 12 print(string) 13 14 # bytes转字符串方式二 15 b = b'\xe9\x80\x86\xe7\x81\xab' 16 string = b.decode() # 第一参数默认utf8,第二参数默认strict 17 print(string) 18 19 # bytes转字符串方式三 20 b = b'\xe9\x80\x86\xe7\x81haha\xab' 21 string = b.decode('utf-8', 'ignore') # 忽略非法字符,用strict会抛出异常 22 print(string) 23 24 # bytes转字符串方式四 25 b = b'\xe9\x80\x86\xe7\x81haha\xab' 26 string = b.decode('utf-8', 'replace') # 用?取代非法字符 27 print(string) 28 29 # 字符串转bytes方式一 30 str1 = '逆火' 31 b = bytes(str1, encoding='utf-8') 32 print(b) 33 34 # 字符串转bytes方式二 35 b = str1.encode('utf-8') 36 print(b)
执行结果
逆火 逆火 逆haha 逆�haha� b'\xe9\x80\x86\xe7\x81\xab' b'\xe9\x80\x86\xe7\x81\xab'
成员操作符 in
1 str = "string test string test" 2 find1 = "str" 3 find2 = "test" 4 print(find1 in str) # True 5 print(find1 not in str) # False
偷偷说一句:in不只是在字符串中可以使用哦!期待后面的教程叭
使用字符串对象的
-
find()
-
rfind()
-
index()
-
rindex()
1 str = "string test string test" 2 find1 = "str" 3 find2 = "test" 4 # find 5 print(str.find(find1)) # 0 6 print(str.find(find2)) # 7 7 8 # rfind 9 print(str.rfind(find1)) # 12 10 print(str.rfind(find2)) # 19 11 12 # index 13 print(str.index(find1)) # 0 14 print(str.index(find2)) # 7 15 16 # rindex 17 print(str.rindex(find1)) # 12 18 print(str.rindex(find2)) # 19 19 20 # count 21 print(str.count(find1)) # 2 22 print(str.count(find2)) # 2
find()和index()的区别
方法 | 区别 |
find() | 获取值时,如果要查找的值不存在,会返回-1 |
index() | 获取值的索引时,如果不存在值,会报错 |
find()和rfind()的区别
方法 | 区别 |
find() | 从字符串左边开始查询子字符串匹配到的第一个索引(从0开始) |
rfind() | 从字符串右边开始查询字符串匹配到的第一个索引(从0开始) |
index()和rindex()的区别
方法 | 区别 |
index() | 从字符串左边开始查询子字符串匹配到的第一个索引(从0开始) |
rindex() | 从字符串右边开始查询字符串匹配到的第一个索引(从0开始) |
转载请注明:XAMPP中文组官网 » Python教程之字符串全部示例详解