深入浅出掌握 Python 字符串|学习笔记

简介: 快速学习深入浅出掌握 Python 字符串

开发者学堂课程【Python 开发基础入门深入浅出掌握 Python 字符串】学习笔记,与课程紧密联系,让用户快速学习知识。

课程地址:https://developer.aliyun.com/learning/course/556/detail/7660


深入浅出掌握 Python 字符串


内容介绍:

一、 字符串

二、 字符串定义 初始化

三、 字符串元素访问一下标

四、 字符串join连接*

五、 字符串+连接

六、 字符串分割

七、 字符串大小写

八、 字符串排版

九、 字符串修改*

十、 字符串查找*

十一、字符串判断*

十二、字符串判断is系列

十三、列表练习

 

一、 字符串

1. 字符串妙用无穷,本质上字符串把内存中的,如果当成字符,那他就是字符串,但是不知道对应的是英文字符还是中文字符,其实在内存中都是二进制的数字

2. 字符串是由一个个字符组成的有序的序列,是字符的集合,并且他可以索引,还可以迭代,可索引和可迭代是两个概念,是一个集合的概念

3. 使用单引号、双引号、三引号引|住的字符序列

a) 空字符串长度为0,等价于false,空字符串就是空集合

4. 字符串是不可变对象,在原基础上就地修改是不可以的,所谓的可变都是拼接出新的字符串

5. Python3起,字符串就是Unicode类型,python3中默认就是utf-8

 

二、 字符串定义 初始化

举例

s1 = 'string'  简单定义

s2 = "string2" 双引号定义

s3 = "this's a "String 三引号定义,其中还能再写单引号和双引号

s4 = 'hello \n magedu.com' 加了特殊转义字符

s5 = r"hello \n magedu.com"添加r,告诉其中\n不再是转义字符,就是普通字符

s6 = 'c:\windows\nt'这个转义字符会实现

s7 = R"c:\windows\nt"添加r,告诉其中\n不再是转义字符,大小r都可以

s8 = 'c:\windows\\nt'添加斜杠进行转义

sql = “””select * from user where name= 'tom'”””

三引号主要用于内容里面有很多其他符号,包括里面出现的单双引号

 

三、字符串元素访问一下标

字符串是由一个个字符组成的有序的序列,是字符的集合,类似于元组

字符串支持使用索引|访问

sql = "select * from user where name ='tom'”

运行以上代码

输入sql进行查看:"select * from user where name ='tom'”

For c in sql:

Print(c)

输出结果

可以看出对sql里面的内容进行了迭代(遍历)其中空格也是,属于一个空白的字符,还有其他看不见的字符

为了了解的更加清楚:查看addresss地址

Address  0 1 2 3 4 5 6 7 8 9 a b c d e f Dump

00000000 61 62 63 20 64 65 09 Od 0a 31 32 33 34 abc de.. . 1234

逢二进一

转换为utf-8后,0b就会丢了,这就是编码不同,Linux的记事本放在windows就会变成一行

查看编码视图,LF代表回车,箭头代表Tab

因为这是一个索引,并且是有序的,所以可以进行迭代

再次运行sql = "中国

运行For c in sql:

Print(c)

显示:

中国

这是一个个字符迭代的结果

运行:sql[0]

输出:‘中‘

记住:Python3起,字符串就是Unicode类型,python3中默认就是utf-8

sql[4] #字符串'C'//通过一个索引来访问sql第4个字节

sql[4]= 'o'

有序的字符集合,字符序列

forc in sql:

print(C)

print(type(C)) #什么类型?

输入:

for  c in sql:

print(c)

print(type(c))

输出:

代表这是字符串类型(没有字符类型)

可迭代

lst = list(sql)

运行得出:[‘’,’’]

list(可迭代的)因为他是一个连续的序列

 

四、字符串join连接*

"string".join(iterable) -> str

输入””.join(sql)

输出:‘中国‘

输入”-”.join(sql)

输出:‘中-国‘

意思是用引号中的内容把sql引用起来

运行lst = list(range(5))

然后运行:’~~~~~’.join(lst)

报错,我们进行修改,把lst中的内容都改为str

运行’~~~~~’.join(map(str,lst))

得到结果:‘0~~~1~~~2~~~3~~~4

这就是map函数的好用之处

将可迭代对象连接起来,使用string作为分隔符

可迭代对象本身元素都是字符串,否则就会出问题

返回一个新字符串

lst = [1',;2',3]

print("\"".join(Ist))#分隔符是双引号

print(" ".join(lst))

print(" \n" .join(lst))

运行print(“\n”.join((‘a’,’b’)))

输出得到结果:

a

b

这是一种join换行的方式

lst = ['1',['a';'b'],3']

print(" ".join(lst))

运行上列代码报错

修改代码lst = ['1',['a';'b'],3']

print("\n ".join(lst))

运行报错,再次修改:

lst = ['1',['a';'b'],3']

print("\n ".join(map(str,lst)))

运行成功:

1

[‘a’,’b’]

3

进行了str的强转

 

五、字符串+连接

相当于返回了一个新的对象

+-> str

2个字符串连接在一起,字符串本身并没有修改

返回一个新字符串,新字符串一旦形成,也是不可变的

运行”abc”*3

得到:abcabcabc

乘法相当于把元素内容重复几遍进行链接输出

 

六、字符串分割

分割字符串的方法分为2类

split系

str.split(sep=None, maxsplit=-1)使用方法

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus,the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (allpossible splits are made).

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, ' 1.,.2' . split(',') returns [1",”,'2' ]). The sep argument may consist of multiple characters (for example, ' 1<>2<>3* . split('<>' ) returns ['1','2','3' ]). Spltting an empty string with a specifed separator returns ['].

将字符串按照分隔符分割成若干字符串,并返回列表

partition系

将字符串按照分隔符分割成2段,返回这2段和分隔符的元组

运行:”a,b,c”.spilt()

得到结果:[‘a’,’b’,’c’]

运行:”a,b\tc”.spilt(‘’)

得到结果:[‘a’,’b\tc’]

运行:”a,b,c”.spilt()空值相当于None

得到结果:[‘a’,’b’,’c’]

”a,b\tc”.spilt(None)

”a,b\tc”.spilt()

”a,b\tc”.spilt(sep=None)

以上三个写法是等价的

链接至少一个空白字符

运行:"a   b    c".split()

得到:['a', 'b', 'c']

再次运行"a   b    c".split( )

得到:['a', '', '', 'b', '', '', '', 'c']

结论:除了按照默认方式外,其他的都用的split中的‘ ‘,这样创造了很多无用的参数,最常用的就是split()

Join和split串联’,’.join(‘abc’).split(‘,’)

运行得到:['a', 'b', 'c']

运行”a,b,c,d,e”.spilt(‘,’,2)其中数字代表最大切割数

结果:['a', 'b', 'c,d,e']

运行”a,b,c,d,e”.rspilt(‘,’,2)其中数字代表最大切割数,其中r代表反方向切割

结果:['a,b,c', 'd', 'e']

运行map(str,[1,2,3])

得到map对象地址,并且这个对象是可以迭代的

split(sep=None, maxsplit=-1) -> list of strings

从左至右

sep指定分割字符串,缺省的情况下空白字符串作为分隔符

maxsplit指定分割的次数,-1表示遍历整个字符串

s1 ="I'm \ta super student."

s1.split()

s1.split('s')s1.split('super')s1.split('super ')s1.split(' ')

s1.split(' ',maxsplit=2)s1.split("\t",maxsplit=2)

rsplit(sep=None, maxsplit=-1) -> list of strings

maxsplit表示最大切割数,r表示反向切割

从右向左

sep指定分割字符串,缺省的情况下空白字符串作为分隔符

maxsplit指定分割的次数,-1表示遍历整个字符串

s1 = "T'm \ta super student."

s1.rsplit()

s1.rsplit('s')s1.rsplit('super')s1.rsplit('super ')s1.rsplit(' ')

s1.rsplit('',maxsplit=2)

splitlines([keepends]) - > list of strings,不支持正则表达式

keepends:是否保留尾巴(其中的转义字符)

提供按照行来切分字符串

keepends指的是是否保留行分隔符

行分隔符包括\n、\rn、\r等

'ab c\n\nde fg\rklIrin'.splitlines()

运行得到:['ab c', '', 'de fg', 'klIrin']

一般不带末尾的true

'ab c\n\nde fg\rklr\n'.splitlines(True)

s1 =""I'm a super student.

You're a super teacher."

print(s1)

print(s1.splitlines(0)print(s1.splitlines(True))

partition(sep)-> (head, sep, tail)返回的叫做三元组,分别是头部,分隔符,尾部,用起来相当于一个简单的split(),把其中的元素变为几个不可变的元组类。

str. partition(sep)使用方法

Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.

运行"a,b,c,d,e".partition(',')

得到:('a', ',', 'b,c,d,e')

这返回的是一个元组,不能修改其中的内容,一刀两断,中间加上分隔符,partition中没有默认值,需要至少添加一个

用c元素来进行切割

运行:"a,b,c,d".partition('c')

结果('a,b,', 'c', ',d')

还可以用,c,来进行切割, ,c,作为一个整体来进行切割

运行:"a,b,c,d".partition(',c,')

结果('a,b,', ',c,', ',d')

从左至右,遇到分隔符就把字符串分割成两部分,返回头、分隔符、尾三部分的三元组;如果没有找到分隔符,就返回头、2个空元素的三元组

sep 分割字符串,必须指定

s1 = "T'm a super student."

s1.partition('s')

s1.partition('stu')

s1.partition("")

s1.partition('abc')

rpartition(sep) -> (head, sep, tail)

str. rpartition(sep)使用方法

Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, andthe part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.

从右至左,遇到分隔符就把字符串分割成两部分,返回头、分隔符、尾三部分的三没有找到分隔符,就返回2个空元素和尾的三元组

 

七、字符串大小写

upper()

upper()使用方法

Return a copy of the string with all the cased characters [4] converted to uppercase. Note that str. upper 0. isupper O might be False if

s contains uncased characters or if the Unicode category of the resulting character(s) is not "Lu" (Letter, uppercase), but e.g.

Lt" (Letter, tlecase).

全大写

lower()

全小写

大小写,做判断的时候用

swapcase()

交互大小写(大写转小写。小写转大写)

输入"abc".upper()运行

结果:'ABC'

再次运行:"abc".upper().lower() 这就叫做链式

结果:'abc'

a = input('>>>')

if a.lower () ='exit': # Exit

pass

因为input函数只会返回字符串,不会返回其他内容的

这样输入大写的也会自动转为小写

 

八、字符串排版

title() -> str,title返回一个字符串

标题的每个单词都大写

输入:’abc def’. title()

输出Abc Def

capitalize() -> str首字母大写

首个单词大写

输入:’abc def’. capitalize()

输出Abc def

center(width[, fillchar]) -> str

width打印宽度

输入:’123’. center (50)

输出’               123                   ’

 输入:’123’. center (50,@)//第二个参数为填充的字符

输出’@@@@@@@@@@@@@123@@@@@@@@@@@@@@@@’

fillchar填充的字符

zfill(width) -> str

width打印宽度,居右,左边用0填充

输入:’123’. zfill (10)

输出’00000000000000000000123’

ljust(width[, fillchar]) -> str左对齐

输入:’123’. ljust (10,’@’)

输出’123@@@@@@@@@@@@@@@@’

rjust(width[, fillchar]) -> str右对齐

输入:’123’. rjust (10,’@’)

输出’ @@@@@@@@@@@@@@@@123’

以上内容中文用的少,了解一下


九、字符串修改*

replace(old, new[, count]) -> str

字符串中找到匹配替换为新子串,A返回新字符串

count表示替换几次,不指定就是全部替换

字符串是不可变类型,返回都是返回一个新的字符串

找到旧的字符串进行替换,其中有替换多少次,替换的过程其实有一个搜索的过程 ,替换时必须从左到右遍历一遍

'www.magedu.com'.replace('w',"p')

功能:遇到一个w就替换为p

'www.magedu.com'.replace('w','p',2)'

功能:w替换为p,一个替换两次

www.magedu.com'.replace('w','p',3)

功能:w替换为p,一个替换三次

‘www.magedu.com'.replace('ww','p,2)

运行以上代码得到结果:'pw.magedu.com'

由此可见功能为:把ww替换为p,因为代码中只有三个w,所以只替换了一次

再次运行'www.magedu.com'.replace('ww','w',2)

得到:'ww.magedu.com'

这是一个原则问题,不在回头执行,只往前

‘www.magedu.com'.replace('www';'python',2)

功能:www替换为python

所谓替换就是改掉之前的内容,生成一个新的字符串

字符串修改*

strip([chars])-> str

strip([chars])使用方法

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set ofcharacters to be removed. If omitted or None, the chars argument defaults to removingwhitespace. The chars argument is not a prefixor suffix; rather, all combinations of its values are stripped:

从字符串两端去除指定的字符集chars中的所有字符

如果chars没有指定,去除两端的空白字符

运行:'     a b c \td\re\n123\n\n'.strip()

得到:'a b c \td\re\n123'

结论:去掉两边的空白字符,strip碰到一个空白字符停止

运行:s = "\r \n \t Hello Python \n \t"

s.strip()

结果:'Hello Python'

运行:s = " I am very sorry "

s.strip(‘ overys’)

结果:’I am’

遇到的字符集,从两边看进行清除

一般都只会用s.strip()来清除两边的空格

s.strip('Iy')

s.strip('Ty ')

lstrip([chars]) -> str

从左开始查找清除

rstrip([chars]) -> str

从右开始查找清除

 

十、字符串查找*

find(sub[, start[, end]]) -> int

sub:子字符串

在指定的区间[start, end),从左至右,查找子串sub。找到返回索引,没找到返回-1

rfind(sub[, start[, end]])-> int

bytearray. rfind(sub[, start[, end])使用方法

Return the highest index in the sequence where the subsequence sub is found, such that sub is contained within s[start :end].Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.

Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.

口在指定的区间[start, end),从右至左,查找子串sub。找到返回索引,没找到返回-1

s = "I am very sorry"

运行:s.find('very')

结果:5,找到了,是第五个字节

运行:s.find('lvery')

结果:-1,找不到,返回-1

运行:s.find('very', 5)

结果:5,从第五个开始找

运行:s.find('very', 6,13)

结果:-1,找不到,返回-1

原因:给的13,字节不够找

运行:s.find('very',6 )

结果:10

运行:s.rfind('very', 10)

结果:15

运行:s.rfind('very', 10, 15)

结果:10

运行:s.rfind('very',-10,-1)

结果:15

运行 list(enumerate(s)) 进行查看方便理解:

结果:

[(0, 'I'),(1, ' '),(2, 'a'),(3, 'm'),(4, ' '),

(5, 'v'),(6, 'e'),(7, 'r'),(8, 'y'),(9, ' '),

(10, 'v'),(11, 'e'), (12, 'r'), (13, 'y'),

(14, ' '),(15, 'v'),(16, 'e'),(17, 'r'), (18, 'y'),

(19, ' '), (20, 's'), (21, 'o'),(22, 'r'),

(23, 'r'), (24, 'y')]

 

Index方法

字符串查找*

index(sub[, start[, end]) -> int

在指定的区间[start, end) ,从左至右,查找子串sub。找到返回索引,没找到抛出异常ValueError

rindex(sub[, start[ end]])-> int

在指定的区间[start, end) ,从左至右,查找子串sub。找到返回索引,没找到抛出异常ValueError

s= "I am very sorry"

s.index('very')

s.index('very', 5)

s.index('very', 6, 13)

s.rindex("very', 10)

s.rindex('very', 10, 15)

s.rindex('very',-10,-1)

平常都使用find方法,因为index方法会抛出异常,比较麻烦和find用法一模一样

 

字符串查找

时间复杂度

index和count方法都是O(n)

随着列表数据规模的增大,而效率下降,效率越来越低

所以优先考虑索引

len(string)

返回字符串的长度,即字符的个数

count(sub[, start[, end]])-> int

在指定的区间[start, end),从左至右,统计子串sub出现的次数

也要进行遍历,时间复杂度也是很高的

s = "I am very sorry"

s.count('very')

s.count('very', 5)

s.count('very', 10,14)

 

十一、字符串判断*

endswith(suffix[, start[, end]]) -bool

suffix:以什么为后缀

在指定的区间[start, end),字符串是否是suffix结尾

startswith(prefix[, start[, end]l)->bool

prefix:以什么为前缀

在指定的区间[start, end),字符串是否是prefix开头

s = "I am very sorry"

s.startswith('very')

s.startswith('very', 5)

s.startswith('very', 5, 9)

s.endswith('very', 5. 9)

s.endswith('sorry', 5)

s.endswith('sorry',5, -1)

运行:s.endswith('sorry', 5, 100)

结果:True

多了一个空格

运行:'sorry '.endswith('sorry', 0, -1)

结果:True

 

十二、字符串判断is系列

isalnum()-> bool是否是字母和数字组成

运行:“abc123”. isalnum()

结果:True

isalpha()是否是字母

isdecimal()是否只包含十进制数字

isdigit()是否全部数字(O~9)

isidentifier()是不是字母和下划线开头,其他都是字母、数字、下划线(标识符)

运行:“abc123”. isidentifier()

结果:True

islower()是否都是小写

isupper()是否全部大写

isspace()是否只包含空白字符

运行:“ \t\r\n”. isspace()

结果:True

运行:“ \t\1r\n”. isspace()

结果:False

image.png

计算杨辉三角前6行

下一行依赖上一行所有元素,是上一行所有元素的两两相加的和,再在两头各加1

triangle=[[1],[1,1]]

//遍历

for i in range(2,6):

cur =[1]

pre = triangle[i-1]

for j in range(len(pre)-1):

cur.append(pre[j]+prelj+1])

cur.append(1)

triangle.append(cur).

print(triangle)

相关文章
|
3天前
|
存储 索引 Python
字符串、列表、元组、字典(python)
字符串、列表、元组、字典(python)
|
6天前
|
数据采集 开发者 Python
在Python中判断字符串中是否包含字母
在Python中判断字符串中是否包含字母
20 4
|
5天前
|
Python
python之字符串定义、切片、连接、重复、遍历、字符串方法
python之字符串定义、切片、连接、重复、遍历、字符串方法
6 0
python之字符串定义、切片、连接、重复、遍历、字符串方法
|
13天前
|
Python
GitHub爆赞!终于有大佬把《Python学习手册》学习笔记分享出来了
这份笔记的目标是为了给出一份比较精炼,但是又要浅显易懂的Python教程。《Python学习手册》中文第四版虽然比较简单,但是措辞比较罗嗦,而且一个语法点往往散落在多个章节,不方便读者总结。 我在做笔记时,将一个知识点的内容都统筹在一个章节里面,因此提炼性大大提高。而且还有《Python学习手册》中文第四版的翻译在某些章节(可能难度较大?)措辞可能前后矛盾。当知识点提炼之后就能够很快的找到一些难以理解的概念的上下文,方便吃透这些难点。
GitHub爆赞!终于有大佬把《Python学习手册》学习笔记分享出来了
这份笔记的目标是为了给出一份比较精炼,但是又要浅显易懂的Python教程。《Python学习手册》中文第四版虽然比较简单,但是措辞比较罗嗦,而且一个语法点往往散落在多个章节,不方便读者总结。 我在做笔记时,将一个知识点的内容都统筹在一个章节里面,因此提炼性大大提高。而且还有《Python学习手册》中文第四版的翻译在某些章节(可能难度较大?)措辞可能前后矛盾。当知识点提炼之后就能够很快的找到一些难以理解的概念的上下文,方便吃透这些难点。
|
16天前
|
Python 索引
【Python字符串攻略】:玩转文字,编织程序的叙事艺术
【Python字符串攻略】:玩转文字,编织程序的叙事艺术
|
16天前
|
Python
刷题——Python篇(3)字符串
刷题——Python篇(3)字符串
|
4天前
|
索引 Python 容器
深入探索Python字符串:技巧、方法与实战
深入探索Python字符串:技巧、方法与实战
|
4天前
|
Python
python3 入门学习笔记
python3 入门学习笔记
5 0
|
5天前
|
Python
Python 字符串格式化的方式有哪些?
这篇文章主要介绍了Python的字符串格式化方法,包括: 1. `%` 操作符,如 `%s`, `%d`, `%f` 用于基本的变量插入和类型转换。 2. `str.format()` 方法,利用 `{}` 占位符和位置或关键字参数。 3. f-strings (Python 3.6+),直接在字符串前加 `f` 并在花括号内嵌入变量。 4. `string.Template` 模块,使用 `$` 符号进行模板替换。 5. `str.format_map()` 方法,接受字典替换占位符。 文章强调f-strings在新代码中的推荐使用,因其简洁和可读性。