在此谢谢Datawhale提供的资料帮助学习,[1]
为资料来源
1 字符串的定义
(1)Python 中字符串被定义为引号之间的字符集合,引号使用成对的单引号或双引号。
t1 = 'i love Python!' # 单引号
print(t1, type(t1))
# i love Python! <class 'str'>
t2 = "I love Python!" # 双引号
print(t2, type(t2))
# I love Python! <class 'str'>
print(5 + 8) # 13,int之间的相加
print('5' + '8') # 58,有单引号,是字符串之间的相加
所以对于数字的相加要注意,别和string
搞混
(2)常用转义字符
如果字符串中需要出现单引号或双引号,可以使用转义符号\
对字符串中的符号进行转义。或者在书写字符串的时候注意点。(双引号包括单引号或者单引号包括双引号)
\
对\
转义
原始字符串只要在字符串前边加一个英文字母r
即可
\对'转义以及双引号包含单引号
print('let\'s go') # let's go
print("let's go") # let's go
# \对\转义
print('C:\\now') # C:\now
# \对\转义
print("C:\\Program Files\\Intel\\Wifi\\Help")
# C:\Program Files\Intel\Wifi\Help
# 原始字符串只要在字符串前边加一个英文字母r即可
print(r'C:\Program Files\Intel\Wifi\Help')
# C:\Program Files\Intel\Wifi\Help
三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符。
在下面的例子可以看出:\t
是TAB
如果在末尾,看起来对下一行没有影响。而\n
如果在末尾,对下一行是有影响的。(这里的影响怪怪的)
para_str = """这是一个多行字符串的实例
多行字符串可以使用制表符
TAB
\tTAB。
TAB\t
TAB。
也可以使用换行符
\n也可以使用换行符
也可以使用换行符\n
也可以使用换行符
"""
print(para_str)
# 这是一个多行字符串的实例
# 多行字符串可以使用制表符
# TAB
# TAB。
# TAB
# TAB。
# 也可以使用换行符
#
# 也可以使用换行符
# 也可以使用换行符
#
# 也可以使用换行符
2 字符串的切片和拼接
(1)类似于元组具有不可修改性
(2)从 0 开始
(3)切片通常写成 start:end
这种形式,包括「start 索引
」对应的元素,不包括「end索引
」对应的元素。
(4)索引值可正可负,正索引从 0 开始,从左往右;负索引从 -1 开始,从右往左。
使用负数索引时,会从最后一个元素开始计数。最后一个元素的位置编号是 -1。
注意一个空格也是一个字符
下面的例子主要看看str的+
关于拼接,如果本身是字符串,直接就是str1[a:b]
,如果不是,就使用双引号或者单引号使其变成字符串
str1 = 'I Love LsgoGroup'
print(str1[:6]) # I Love
print(str1[5]) # e
print(str1[:6] + " 插入的字符串 " + str1[6:])
# I Love 插入的字符串 LsgoGroup
s = 'Python'
print(s) # Python
print(s[2:4]) # th
print(s[-5:-2]) # yth
print(s[2]) # t
print(s[-1]) # n
3 字符串的常用内置方法
(1)capitalize()
将字符串的第一个字符转换为大写。
(2)lower()
转换字符串中所有大写字符为小写。
(3)upper()
转换字符串中的小写字母为大写。
(4)swapcase()
将字符串中大写转换为小写,小写转换为大写。
str2 = 'xiaoxie'
print(str2.capitalize()) # Xiaoxie
str2 = "DAXIExiaoxie"
print(str2.lower()) # daxiexiaoxie
print(str2.upper()) # DAXIEXIAOXIE
print(str2.swapcase()) # daxieXIAOXIE
(5)count(str, beg= 0,end=len(string))
返回str
在 string
里面出现的次数,如果beg
或者end
指定则返回指定范围内str
出现的次数。
str2 = "DAXIExiaoxie"
print(str2.count('xi')) # 2
(6)endswith(suffix, beg=0, end=len(string))
检查字符串是否以指定子字符串 suffix
结束,如果是,返回 True
,否则返回 False
。如果 beg
和 end
指定值,则在指定范围内检查。
startswith(substr, beg=0,end=len(string))
检查字符串是否以指定子字符串 substr
开头,如果是,返回 True
,否则返回 False
。如果 beg
和 end
指定值,则在指定范围内检查。
str2 = "DAXIExiaoxie"
print(str2.endswith('ie')) # True
print(str2.endswith('xi')) # False
print(str2.startswith('Da')) # False
print(str2.startswith('DA')) # True
(7)find(str, beg=0, end=len(string))
检测 str
是否包含在字符串中,如果指定范围 beg
和 end
,则检查是否包含在指定范围内,如果包含,返回开始的索引值,否则返回 -1。
rfind(str, beg=0,end=len(string))
类似于 find()
函数,不过是从右边开始查找。
str2 = "DAXIExiaoxie"
print(str2.find('xi')) # 5
print(str2.find('ix')) # -1
print(str2.rfind('xi')) # 9
D A X I E x i a o x i e
0 1 2 3 4 5 6 7 8 9 10 11
(8)isnumeric()
如果字符串中只包含数字字符,则返回 True
,否则返回 False
。
str3 = '12345'
print(str3.isnumeric()) # True
str3 += 'a'
print(str3.isnumeric()) # False
str3="1235A"
print(str3.isnumeric()) # False
(9)ljust(width[, fillchar])
返回一个原字符串左对齐,并使用fillchar
(默认空格)填充至长度width
的新字符串。
rjust(width[, fillchar])
返回一个原字符串右对齐,并使用fillchar
(默认空格)填充至长度width
的新字符串。
str4 = '1101'
print(str4.ljust(8, '0')) # 11010000
print(str4.ljust(6,'s')) # 1101ss
print(str4.rjust(8, '0')) # 00001101
print(str4.rjust(7,'p')) # ppp1101
(10)lstrip([chars])
截掉字符串左边的空格或指定字符。
rstrip([chars])
删除字符串末尾的空格或指定字符。
strip([chars])
在字符串上执行lstrip()
和rstrip()
。
- 上面这句话怎么理解比较好?在字符串上执行?
源于[2]
如果strip()
的参数为空,那么会默认删除字符串头和尾的空白字符(包括\n
,\r
,\t
这些)
指定单个参数str
,会删除前导和后缀str
lstrip
就是单独指前导,rstrip
单独指后缀
以及[3]
lstrip = left strip =去除(字符串)左边的=stip leading=去除(字符串)开始的
rstrip = right strip =去除(字符串)右边的=strip trailling=去除(字符串)末尾的
strip = stip left and right = 去除(字符串的)左边的和右边的=strip leading and trailing = 去除(字符串)开始的和末尾的
name.contents[0].strip().rstrip(‘,’)
等价于
name.contents[0].strip(None).rstrip(‘,’)
解读:对于name.contents[0]
, 先去除首尾(即头部和尾部)的白空格(空格本身,回车\r
,换行\n
,制表符\t
, 换页符\f
) 之后,再去除尾部的逗号’,
’
以下是(10)的练习题,加了逗号是为了方便看
str5 = ' I Love LsgoGroup '
print(len(str5)) # 18
print(str5.lstrip()) # 'I Love LsgoGroup ' 删除字符串左边的空格
print(len(str5.lstrip())) # 17
print(str5.lstrip('I')) # ' I Love LsgoGroup ' 没有删除字符串左边空格,也没有删除I
print(len(str5.lstrip('I'))) # 18
# 所以lstrip()删除字符串左边的空格,lstrip('str')无影响
# 上面是错误的理解,所以要划掉
# 之所以lstrip('str')没有反应没有删除I,是因为str5的首是空格不是I
print(str5.lstrip().strip('I')) # ' Love LsgoGroup '删除字符串左边的I及空格
print(len(str5.lstrip().strip('I'))) # 16
print(str5.strip('I').lstrip()) # 'I Love LsgoGroup '删除了左边的空格,没有删除I
print(len(str5.strip('I').lstrip())) # 17
# lstrip().strip('I') 删除字符串左边的空格以及左边的I
# strip('I').lstrip() 删除字符串左边的的空格,没有删除I
# 所以lstrip().strip('str') √ strip('str').lstrip() ×
# 上面的理解也是错误的,str5.lstrip().strip('I')逻辑顺序应该是lstrip()先是删除了字符串左边的空格,接着用strip()删除了左边的I
# 接着str5.strip('I').lstrip()是strip('I')没有找到首是I,所以没有删除,首是空格,利用lstrip()删除了空格
print(str5.rstrip()) # ' I Love LsgoGroup' # 删除字符串右边的空格
print(len(str5.rstrip())) # 17
print(str5.strip()) # 'I Love LsgoGroup' # 删除字符串左边和末尾的空格
print(len(str5.strip())) # 16
# rstrip()删除右边的空格,strip()删除首尾的空格
print(str5.strip('I')) # I Love LsgoGroup
print(len(str5.strip('I'))) # 18
# 单独一个strip('str')无影响
# 上面的理解也是错的,str5.rstrip()删除了右边的空格字符串
# 接着str5.strip()删除了左边和右边的空格字符串
# 最后的str5.strip('I')没有删除I
str5='I Love LsgoGroup '
print(len(str5)) # 17
print(str5.strip('I'))
print(len(str5.strip('I')))
# Love LsgoGroup
# 16
# 之前说单独一个strip('str')无影响,我错了,当时前面有空格,一个空格算一个字符串
# 当我把空格delete后,strip('I')出现在首的I就消失了,末尾没有消失(因为末尾没有I并且有空格)
str5='I Love LsgoGroupI'
print(len(str5)) # 17
print(str5.strip('I'))
print(len(str5.strip('I')))
# Love LsgoGroup
# 15
# 此一条就把末尾空格消除了并且加上了I,使用strip('I')消除了首和末的I
str5='I Love LsgoGroupI '
print(len(str5)) # 18
print(str5.strip('I'))
print(len(str5.strip('I')))
# Love LsgoGroupI
# 17
# 当末尾有空格和I的时候,并且空格在I的后面,也是无法消除I
str5 = ' I Love LsgoGroup '
print(len(str5)) # 18
print(str5.strip().strip('p')) # 'I Love LsgoGrou'删除字符串右边的p及空格
print(len(str5.strip().strip('p'))) # 15
# strip().strip('str') 删除首尾的空格并且删除str字符
# str5.strip().strip('p')先删除左右的空格,接着删除左右的p(只有右边有p)
str5 = ' I Love LsgoGroupp '
print(str5.strip().strip('p')) # 'I Love LsgoGrou 删除了字符串右边的两个P和空格
print(len(str5.strip().strip('p'))) # 15
str5 = ' I Love LsgoGropupp '
print(str5.strip().strip('p')) # 'I Love LsgoGropu' 删除了字符串右边的两个P和空格,不过隔着u的p没有删除
print(len(str5.strip().strip('p'))) # 16
# str5.strip().strip('p')先删除左右的空格,再删除左右的p
# str5.strip().strip('p')先删除左右的空格,再删除左右的p,对于右边还有一个隔着的p就无法删除了6
也就是如上所示:
单独一个strip('str')
无影响,如果是单独一个strip()
是默认删除前后的空格
单独一个rstrip()
或者lstrip()
是会删除末或者首的空格,而单独一个rstrip('str)
或者lstrip('str')
是没有反应的
当二者结合,lstrip().strip('str')
删除首的空格和str字符串,而strip('str').lstrip()
是删除首的空格,对str字符串无反应
(11)partition(sub)
找到子字符串sub
,把字符串分为一个三元组(pre_sub,sub,fol_sub)
,如果字符串中不包含sub
则返回(‘原字符串’,’’,’’)。
rpartition(sub)
类似于partition()
方法,不过是从右边开始查找。
str5 = ' I Love LsgoGroup '
print(str5.strip().partition('o'))
# ('I L', 'o', 've LsgoGroup') 找到o分成三元组,o在中间是sub,前面是pre_sub,后者是fol_sub
print(str5.strip().partition('m'))
# ('I Love LsgoGroup', '', '') 找不到m就返回('原字符串','','')
print(str5.strip().rpartition('o'))
# ('I Love LsgoGr', 'o', 'up')
str5 = ' I Love LsgoGrouoop ' # 多加个o
print(str5.strip().partition('o'))
# ('I L', 'o', 've LsgoGrouoop')
print(str5.strip().partition('m'))
# ('I Love LsgoGrouoop', '', '')
print(str5.strip().rpartition('o'))
# ('I Love LsgoGrouo', 'o', 'p')
(12)replace(old, new [, max])
把 将字符串中的old
替换成new
,如果max
指定,则替换不超过max
次
str5=" 123643 5631 5482 1863 45 "
print(str5)
print(len(str5))
# 123643 5631 5482 1863 45
# 26
# 包括了首位和末尾前后两个空格,注意是从1开始
print(str5.strip().replace('1', 'LL'))
print(len(str5.strip().replace('1', 'LL')))
print(str5)
print(len(str5))
# LL23643 563LL 5482 LL863 45
# 27
# 123643 5631 5482 1863 45
# 26
# 前后空格都替换了
print(str5.lstrip().replace('1', 'LL'))
print(len(str5.lstrip().replace('1', 'LL')))
print(str5)
print(len(str5))
# LL23643 563LL 5482 LL863 45
# 28
# 123643 5631 5482 1863 45
# 26
# 之前是27现在是28,说明左边的空格没有替换掉
print(str5.rstrip().replace('1', 'LL'))
print(len(str5.rstrip().replace('1', 'LL')))
print(str5)
print(len(str5))
# LL23643 563LL 5482 LL863 45
# 28
# 123643 5631 5482 1863 45
# 26
# 同上
print(str5.replace('1','LL'))
print(len(str5.replace('1','LL')))
print(str5)
print(len(str5))
# 这里直接使用了replace
# LL23643 563LL 5482 LL863 45
# 29
# 123643 5631 5482 1863 45
# 26
# 貌似直接使用就不删除前后末尾的空格了7+5+4+5+2=23 23+1+1+1+1+1+1=23+6=29
print(str5.replace('1','LL',2))
print(len(str5.replace('1','LL',2)))
print(str5)
print(len(str5))
# LL23643 563LL 5482 1863 45 7+5+4+4+2+6=28
# 28
# 123643 5631 5482 1863 45
# 26
看来用上strip()
是带有删除首位末尾有空格的作用
(13)split(str="", num)
不带参数默认是以空格为分隔符切片字符串,如果num
参数有设置,则仅分隔num
个子字符串,返回切片后的子字符串拼接的列表。
str5 = ' I Love LsgoGroup '
print(str5.strip().split())
# ['I', 'Love', 'LsgoGroup']
print(str5.strip().split('o'))
# ['I L', 've Lsg', 'Gr', 'up']
# 可以看到如果以o为分隔符切片字符串,并且对num参数不设置
print(str5.strip().split('o',2))
# ['I L', 've Lsg', 'Group']
# 以o为分隔符切片字符串,设置好num=2,找了两次o,剩下的自动一起
下面是split
的使用,在没有strip
的基础之上,并且提到了将分割后的部分保存到三个变量
u = "www.baidu.com.cn"
# 使用默认分隔符
print(u.split()) # ['www.baidu.com.cn']
# 以"."为分隔符
print((u.split('.'))) # ['www', 'baidu', 'com', 'cn']
# 分割0次
print((u.split(".", 0))) # ['www.baidu.com.cn']
# 分割一次
print((u.split(".", 1))) # ['www', 'baidu.com.cn']
# 分割两次
print(u.split(".", 2)) # ['www', 'baidu', 'com.cn']
# 分割两次,并取序列为1的项
print((u.split(".", 2)[1])) # baidu
# 分割两次,并把分割后的三个部分保存到三个变量
u1, u2, u3 = u.split(".", 2)
print(u1) # www
print(u2) # baidu
print(u3) # com.cn
利用split()
去掉换行符
c = '''say
hello
baby'''
print(c)
# say
# hello
# baby
print(c.split('\n')) # ['say', 'hello', 'baby']
- 这里没看懂
string = "hello boy<[www.baidu.com]>byebye"
print(string.split('[')[1].split(']')[0]) # www.baidu.com
print(string.split('[')[1].split(']')[0].split('.')) # ['www', 'baidu', 'com']
(14)splitlines([keepends])
按照行(’\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表,如果参数keepends
为 False,不包含换行符,如果为 True,则保留换行符。
str6 = 'I \n Love \n LsgoGroup'
print(str6)
# I
# Love
# LsgoGroup
print(str6.splitlines()) # ['I ', ' Love ', ' LsgoGroup']
print(str6.splitlines(True)) # ['I \n', ' Love \n', ' LsgoGroup']
(15)maketrans(intab, outtab)
创建字符映射的转换表,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
translate(table, deletechars="")
根据参数table给出的表,转换字符串的字符,要过滤掉的字符放到deletechars
参数中。
这里感觉有点像同时替换
str7 = 'this is string example....wow!!!'
intab = 'aeiou'
outtab = '12345'
trantab = str7.maketrans(intab, outtab)
print(trantab) # {97: 49, 111: 52, 117: 53, 101: 50, 105: 51}
print(str7.translate(trantab)) # th3s 3s str3ng 2x1mpl2....w4w!!!
4 字符串格式化
str8 = "{0} Love {1}".format('I', 'Lsgogroup') # 位置参数
print(str8) # I Love Lsgogroup
str8 = "{a} Love {b}".format(a='I', b='Lsgogroup') # 关键字参数
print(str8) # I Love Lsgogroup
str8 = "{0} Love {b}".format('I', b='Lsgogroup') # 位置参数要在关键字参数之前
print(str8) # I Love Lsgogroup
str8 = '{0:.2f}{1}'.format(27.658, 'GB') # 保留小数点后两位
print(str8) # 27.66GB
常用格式化符号
print('%c' % 97) # a
print('%c %c %c' % (97, 98, 99)) # a b c
print('%d + %d = %d' % (4, 5, 9)) # 4 + 5 = 9
print("我叫 %s 今年 %d 岁!" % ('小明', 10)) # 我叫 小明 今年 10 岁!
print('%o' % 10) # 12
print('%x' % 10) # a
print('%X' % 10) # A
print('%f' % 27.658) # 27.658000
print('%e' % 27.658) # 2.765800e+01
print('%E' % 27.658) # 2.765800E+01
print('%g' % 27.658) # 27.658
text = "I am %d years old." % 22
print("I said: %s." % text) # I said: I am 22 years old..
print("I said: %r." % text) # I said: 'I am 22 years old.'
print('%5.1f' % 27.658) # ' 27.7'
print('%.2e' % 27.658) # 2.77e+01
print('%10d' % 10) # ' 10'
print('%-10d' % 10) # '10 '
print('%+d' % 10) # +10
print('%#o' % 10) # 0o12
print('%#x' % 108) # 0x6c
print('%010d' % 5) # 0000000005
5 题目
等待解答
1、字符串函数回顾
怎么批量替换字符串中的元素?
怎么把字符串按照空格进⾏拆分?
怎么去除字符串⾸位的空格?
2、实现isdigit函数
题目要求
实现函数isdigit, 判断字符串里是否只包含数字0~9
def isdigit(string):
"""
判断字符串只包含数字
:param string:
:return:
"""
# your code here
pass
3、leetcode 5题 最长回文子串
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例:
输入: “babad”
输出: “bab”
输入: “cbbd”
输出: “bb”
class Solution:
def longestPalindrome(self, s: str) -> str:
# your code here
[1]https://github.com/datawhalechina/team-learning-program/blob/master/Python-Language/08.%20%E5%AD%97%E7%AC%A6%E4%B8%B2.md
[2]https://blog.youkuaiyun.com/starmoth/article/details/86567016
[3]https://blog.youkuaiyun.com/ialexanderi/article/details/74389002