02Python学习str详解

本文详细介绍了Python中字符串(str)的特点和内置方法,包括count、encode、endswith、startswith、expandtabs等,以及str的各种构造方法和format的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、str特点

​ str为有序字符集,可以切片,可以索引。但是str一旦创建,就无法修改

二、str内置方法及函数

2.1 str对象.count(子序列,起始位置-可选,结束位置-可选)

字符串去匹配子序列出现的次数

>>> s = "11221212"
>>> v1 = s.count("1")
>>> v2 = s.count("12")
>>> v3 = s.count("2",-3)
>>> v4 = s.count("12",1,-5)
>>> print("v1 = " ,v1)
v1 =  4
>>> print("v2 = " ,v2)
v2 =  3
>>> print("v3 = " ,v3)
v3 =  2
>>> print("v4 = " ,v4)
v4 =  1

2.2 str对象.encode(encoding=‘utf-8’, errors=‘strict’)

​ 该方法返回编码后的字符串,它是一个 bytes 对象

>>> s = "我是谁"
>>> v1 = s.encode()
>>> v2 = s.encode(encoding="gbk",errors="ignore")
>>> print("v1 = " ,v1)
v1 =  b'\xe6\x88\x91\xe6\x98\xaf\xe8\xb0\x81'
>>> print("v2 = " ,v2)
v2 =  b'\xce\xd2\xca\xc7\xcb\xad'

2.3 str对象.endswith() && startswith()

2.3.1 endswith(字符子集,起始位置-可选,结束位置-可选)

查看字符是否以该字符来作为结尾

>>> s = "aabbaabbccddee"
>>> v1 = s.endswith("ee")
>>> v2 = s.endswith("de",-8,-1)
>>> print("v1 = " ,v1)
v1 =  True
>>> print("v2 = " ,v2)
v2 =  True

2.3.2 startswith(prefix, start=None, end=None)

>>> s = "aabbaabbccddee"
>>> v1 = s.startswith("aa")
>>> v2 = s.startswith("ab")
>>> v3 = s.startswith("ab",1,-1)
>>> v1
True
>>> v2
False
>>> v3
True

2.4 str对象.expandtabs(tablesize=8)

  • tabsize – 指定转换字符串中的 tab 符号(’\t’)转为空格的字符数。

该方法返回字符串中的 tab 符号(’\t’)转为空格后生成的新字符串。

>>> s = "12\t3"
>>> v1 = s.expandtabs(tabsize=20)
>>> v1
'12                  3'
>>> len(v1)
21
>>> v2 = s.expandtabs()
>>> v2
'12      3'
>>> len(v2)
9

# 应用
>>> s = "My name is %s \t  My age is %d \t My car is %s"
>>> jack = s % ("Jack", 21,"BMW")
>>> john = s % ("John",22,"BEN-Z")
>>> print(jack.expandtabs(20))
My name is Jack       My age is 21       My car is BMW
>>> print(john.expandtabs(20))
My name is John       My age is 22       My car is BEN-Z

2.5 str对象.find() && rfind()

2.5.1 find(sub, start=None, end=None)

Sub - 指定检索的字符串

Start-开始索引,默认为0

End-结束索引,默认为字符串的长度

返回:如果包含子字符串返回开始的索引值,否则返回-1。

>>> s = "aabb123ss1122"
>>> v1 = s.find("1")
>>> v2 = s.find("ab")
>>> v3 = s.find("a",5,-1)
>>> v1
4
>>> v2
1
>>> v3
-1

2.5.2 rfind(sub, start=None, end=None)

refind()类似于 find()函数,不过是从右边开始查找

>>> s = "11AAAAAAa11AAAAAAAAAA11"
>>> print(s.rfind("11"))
21
>>> print(s.rfind("11",0,7))
0
>>> print(s.rfind("11",3,7))
-1

2.6 str对象.format( *args, **kwargs) && format_map(mapping)

2.6.1 format( *args, **kwargs)

2.6.2 format_map(mapping)

2.7 str对象.index() && rindex()

2.7.1 index(sub, start=None, end=None)

sub - 指定检索的字符串

start - 开始索引,默认为0

end = 结束索引,默认为字符串的长度

返回:如果包含子字符串返回开始的索引值

>>> s = "您好,abc,123,abc,您好"
>>> v1 = s.index("您")
>>> v2 = s.index("abc,",7,-1)
>>> v3 = s.index("z")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> v1
0
>>> v2
11
>>> v3
-1

2.7.2 rindex(sub, start=None, end=None)

rindex类似于 index(),不过是从右边开始.

>>> s = "您好,abc,123,abc,您好"
>>> v1 = s.rindex("您")
>>> v2 = s.rindex("abc,",7,-1)
>>> v3 = s.rindex("z")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> v1
15
>>> v2
11
>>> v3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'v3' is not defined

2.8 str对象.isalpha() && isdecimal() && isdigit() && isnumeric() && isalnum()

2.8.1 isalpha()

如果字符串至少有一个字符并且 **所有字符都是字母 **则返回 True, 否则返回 False

>>> print('abc'.isalpha())
True
>>> print('ABC'.isalpha())
True
>>> print('A '.isalpha())
False
>>> print('1'.isalpha())
False
>>> print('0.1'.isalpha())
False
>>> print('1E12'.isalpha())
False
>>> print('一'.isalpha())
True
>>> print('1️⃣'.isalpha())
False
>>> print('①'.isalpha())
False

2.8.2 isdecimal()

检查字符串是否只包含 十进制字符 ,如果是返回 true,否则返回 false。

>>> print('1'.isdecimal())
True
>>> print('A '.isdecimal())
False
>>> print('0.1'.isdecimal())
False
>>> print('1E12'.isdecimal())
False
>>> print('一'.isdecimal())
False
>>> print('1️⃣'.isdecimal())
False
>>> print('①'.isdecimal())
False
>>> print('abc'.isdecimal())
False
>>> print('ABC'.isdecimal())
False

2.8.3 isdigit()

字符串**只包含数字**则返回 True 否则返回 False

>>> print('A '.isdigit())
False
>>> print('1'.isdigit())
True
>>> print('0.1'.isdigit())
False
>>> print('1E12'.isdigit())
False
>>> print('一'.isdigit())
False
>>> print('1️⃣'.isdigit())
False
>>> print('①'.isdigit())
True

2.8.4 isnumeric()

如果字符串中**只包含数字字符**,则返回 True,否则返回 False

>>> print('1'.isnumeric())
True
>>> print('A '.isnumeric())
False
>>> print('0.1'.isnumeric())
False
>>> print('1E12'.isnumeric())
False
>>> print('一'.isnumeric())
True
>>> print('1️⃣'.isnumeric())
False
>>> print('①'.isnumeric())
True

2.8.5 isalnum

如果字符串至少有一个字符并且所有字符都是 字母或数字 则返 回 True,否则返回 False

>>> print('A'.isalnum())
True
>>> print('1'.isalnum())
True
>>> print('1E12'.isalnum())
True
>>> print('一'.isalnum())
True
>>> print('①'.isalnum())
True
>>> print('1️⃣'.isalnum())
False
>>> print('0.1'.isalnum())
False

2.9 str对象.isidentifier()

如果字符串是有效的 Python 标识符返回 True,否则返回 False。

>>> print("_".isidentifier())
True
>>> print("str".isidentifier())
True
>>> print("if".isidentifier())
True
>>> print("while".isidentifier())
True
>>> print(" ".isidentifier())
False
>>> print("(".isidentifier())
False

2.10 str对象.isprintable()

判断字符串的所有字符都是**可打印字符或字符串为空**

>>> print("abcABC123".isprintable())
True
>>> print("May\'s dad".isprintable())
True
>>> print("".isprintable())
True
>>> print(" ".isprintable())
True
>>> print("abc\n".isprintable())
False
>>> print("\tabc".isprintable())
False

2.11 str对象.isspace()

字符串中只包含空白,则返回 True,否则返回 False

>>> print("abc  ABC 123".isspace())
False
>>> print("".isspace())
False
>>> print(" ".isspace())
True
>>> print("\n".isspace())
True
>>> print("\t".isspace())
True

2.12 str对象.istitle() && title()

2.12.1 istitle()

字符串中,英文的首字母都是大写的返回true, 不是则返回flase

>>> print("Hello My Name Is Joe!".istitle())
True
>>> print("我的名字叫Joe!".istitle())
True
>>> print("Hello my name is Joe!".istitle())
False

2.12.2 title()

转换成英文标题样式

>>> "my name is joe,我的名字叫Joe".title()
'My Name Is Joe,我的名字叫Joe'

2.13 str对象.isupper() && islower() && upper() && lower() && swapcase() && capitalize() && casefold()

2.13.1 isupper()

字符串中包含至少一个区分大小写的字符,并且所有这些**(区分大小写的)字符都是大写**,则返回 True,否则返回 False

>>> print("HELLO WORLD".isupper())
True
>>> print("你的我的ABC^&".isupper())
True
>>> print("你的我的^&".isupper())
False

2.13.2 islower()

字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False

>>> print("abc".islower())
True
>>> print("你的我的abc^&".islower())
True
>>> print("Abc".islower())
False
>>> print("123".islower())
False
>>> print("@#%".islower())
False

2.13.3 upper()

转换字符串中所有小写字符为大写

>>> print("AAbbCC  _你我他".upper())
AABBCC  _你我他

2.13.4 lower()

转换字符串中所有大写字符为小写

>>> print("AAbbCC  _你我他".lower())
aabbcc  _你我他

2.13.5 swapcase()

转换字符串中所有大写字符为小写,小写字符为大写

>>> print("AAbbCC  _你我他".swapcase())
aaBBcc  _你我他

2.13.6 capitalize()

首字母大写

>>> s = "abcdefghijklmnopqrstuvwxyz"
>>> v = s.capitalize()
>>> v
'Abcdefghijklmnopqrstuvwxyz'

2.13.7 casefold()

全部转成小写

>>> s = "ABCDEF"
>>> v = s.casefold()
>>> v
'abcdef'

2.14 str对象.join(iterable)

通过字符串对象来循环遍历iterable,并且在每个元素中拼接str对象,iterable为可迭代对象的字符,包括:list/str/dict/

>>> print("*".join(["A","B","V"]))
A*B*V
>>> print("大家好".join("ABCDEF"))
A大家好B大家好C大家好D大家好E大家好F
>>> print("".join(("A","B","C",)))
ABC
>>> print("AA".join(1))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only join an iterable

2.15 str对象.ljust() && rjust() && zfill() && center()

2.15.1 ljust(width, fillchar=None)

返回一个原字符串**左对齐**,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格

>>> print("hellloworld".ljust(50))
hellloworld                                       
>>> print("hellloworld".ljust(50,"*"))
hellloworld***************************************

2.15.2 rjust(width, fillchar=None)

返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串

>>> print("hellloworld".rjust(50))
                                       hellloworld
>>> print("hellloworld".rjust(50,"*"))
***************************************hellloworld

2.15.3 zfill(width)

返回长度为 width 的字符串,原字符串右对齐,前面填充0

>>> print("hellloworld".zfill(50))
000000000000000000000000000000000000000hellloworld

2.15.4 center(width, fillchar=None)

判断字符串长度,如果长度小于参数的长度,使用填充字符来填充

>>> s = "abc"
>>> v = s.center(5,"*")
>>> v
'*abc*'
>>> ss = "1234567"
>>> print(ss.center(10,"!"))
!1234567!!

2.16 str对象.lstrip() && rstrip() && strip()

2.16.1 lstrip(chars=None)

截掉字符串左边的空格或指定字符

>>> print("\t\nAAA\t\n".rstrip())

AAA
>>> print("\t\nAAA\t\n".lstrip())
AAA

>>> 

2.16.2 rstrip(chars=None)

>>> print("\t\nAAA\n\t".rstrip("\t"))

AAA

>>> print("\t\nAAA\n\t".lstrip("\t"))

AAA

>>> 

2.16.3 strip(chars=None)

chars 移除字符串头尾指定的字符序列 , 返回移除字符串头尾指定的字符序列

>>> print("\t\nAAA\n\t".strip())
AAA
>>> print("\t\nAAA\n\t".strip("\t\n"))
AAA

2.17 str对象.maketrans() && translate()

maketrans() 创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标

一般结合translate()使用

>>> old_str = "ABCabc"
>>> new_str = "123456"
#创建字典映射关系
>>> trans_str = str.maketrans(old_str,new_str)
>>> s = "ABCDEFG,abcedfg,Apple is very good!"
#争对字符串进行字段翻译
>>> print(s.translate(trans_str))
123DEFG,456edfg,1pple is very good!

2.18 str对象.partition(sep)

2.18.1 partition(sep)

切割字符串对象,并返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串

>>> s = "Python is so easy use"
>>> print(s.partition(" "))
('Python', ' ', 'is so easy use')

2.18.2 rpartition(sep)

rpartition类似partition,不过是从右边开始

>>> s = "Python is so easy use"
>>> print(s.rpartition(" "))
('Python is so easy', ' ', 'use')

2.19 str对象.replace(old, new, count=None)

把将字符串中的 old 替换成 new,如果 count 指定,则替换不超过 count 次

>>> s = "AbAbBBABABABBbbbaa"
>>> print(s.replace("AB","?"))
AbAbBB???Bbbbaa
>>> print(s.replace("A","?",2))
?b?bBBABABABBbbbaa

2.20 str对象.split() && rsplit() && splitlines()

2.20.1 split(sep=None, maxsplit=-1)

以 sep 为分隔符截取字符串,spe默认为空格换行符制表位,如果 maxsplit 有指定值,则仅截取 maxsplit 个子字符串,并返回一个列表对象

>>> s = "python\n python\n python python"
>>> print(s.split())
['python', 'python', 'python', 'python']
>>> print(s.split("o"))
['pyth', 'n\n pyth', 'n\n pyth', 'n pyth', 'n']
>>> print(s.split("th",3))
['py', 'on\n py', 'on\n py', 'on python']

2.20.2 rsplit(sep=None, maxsplit=-1)

同split一样使用

>>> s = "python\n python\n python python"
>>> print(s.rsplit())
['python', 'python', 'python', 'python']
>>> print(s.rsplit("o"))
['pyth', 'n\n pyth', 'n\n pyth', 'n pyth', 'n']
>>> print(s.rsplit("th",3))
['python\n py', 'on\n py', 'on py', 'on']

2.20.3 splitlines(keepends=None)

按照行(’\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。

>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']

三、str的几种构造方法

>>> s1 = 'hello'
>>> s1
'hello'

>>> s2 = str([1,2,'A'])
>>> s2
"[1, 2, 'A']"

四、str之format详解

>>> s1 = "{},{}".format("q","j")
>>> s1
'q,j'

>>> s2 = "{1},{0}".format("j","Q")
>>> s2
'Q,j'

>>> s3 = "{name},{age}".format(age=18,name="QJ")
>>> s3
'QJ,18'

# ^、<、>分别是居中、左对齐、右对齐,后面带宽度
# :号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
>>> s4 = "{0:^10}".format("A")		# 居中对齐,总共十个占位符
>>> s4
'    A     '

>>> s5 = "{0:<10}".format("A")	#左居中,总共十个占位符
>>> s5
'A         '

>>> s6 = "{0:>10}".format("A")	#右居中,总共十个占位符
>>> s6
'         A'

# 进制format,b、d、o、x分别是二进制、十进制、八进制、十六进制。
>>> s7 = "{:b}".format(20)
>>> s7
'10100'

>>> s8 = "{:d}".format(20)
>>> s8
'20'

>>> s9 = "{:o}".format(20)
>>> s9
'24'

>>> s10= "{0:x}".format(20)
>>> s10
'14'

# 格式化金额
>>> s11 = '{:,}'.format(1000000000)
>>> s11
'1,000,000,000'

# 浮点数精度,存在四舍五入
>>> s12 = "{:.5f}".format(100.1234567)
>>> s12
'100.12346'

# 通过占位符来进行左对齐,长度总共10
>>> s13 = "{:*>10}".format("A")
>>> s13
'*********A'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值