【python超全超详细学习笔记 1--字符串基础】

字符串

1. 字符的编码

ASCII值

ord(字符)返回数字和chr(数字)返回字符配对

2.字符串的遍历

-法1(通过in

str='I_love_code !'
for s in str:
    print(s)

-法2(通过索引range遍历)

str='I_love_code !'
for i in range(len(str)):
    print(str[i])

3.字符串的切片

[x:y]–>[x,y) 左闭右开,右-1

str='I_love_code !'
print(str[2:6])

4.修改字符串

字符串是不可变对象,要想改字符串的某个字符,有以下方法。

-法1 (转来转去)

  • 先把字符串转变成可变对象(如:list列表)
  • 再用join()转回字符串
str='I_love_code !'
lis=list(str)#变成列表
lis[3]='^'#用列表索引修改字符
str=''.join(lis)#合并,每个字符中间填充’‘内的内容,此时为空,就黏在一起了
print(str)

-法2 (用replace()函数)

replace官方文档

  • 使用注意:返回原字符串的副本<=>不会修改原字符串。要用一个variable变量承接,原字符串不会改变 replace(旧的字符串,新的字符串,替换前x个)
str='I_love_code, code and code!'
new=str.replace("code","you",2)#count不可以为负数
print(new)
print(str)
#运行结果如下:
#I_love_you, you and code!
#I_love_code, code and code!

实例:Caesar(凯撒)密码–加密原文

  • 简单说一下凯撒密码的加密方式:
    原字母->向右+5个位置->对应字母表的字母
#加密函数--向右移
def Cencode(str):
    new=" "
    for i in str:
        n=ord(i)-ord("A")#算出原字母对应26个字母表的第几个
        n=(n+5)%26#向右偏移5,就可以算出新字母对应26个字母表的第几个
        new+=chr(n+ord("A"))
    return new
    
#解密函数--向左回移
def Cdecode(str):
    old=" "
    for i in str:
        n=ord(i)-ord("A")
        n=(n-5)%26#对26取余是为了构成循环圈,如果遇到Z就得回到从A开始
        old+=chr(n+ord("A"))
    return old 
  • 核心思想:
  1. 把原字母确定到**26字母表**的第几个位置
  2. “A”的ASCII值有关
  3. %26循环圈
  4. 先设一个new字符串,然后不断向它+字母

5.字符串表达式

  • 字符串放在引号里面 'x', "xx" ,'''xxx''',123都可以

5.1转义字符

  • \’ ,\‘’ ,\t (制表符4个空格) ,\n (换行符) ,\\

5.2按原字符串输出:

  • print里面加一个r/R
print(r"D:\ttest.text")

6.字符串函数

-6.1字母大小写转换upper()&lower()函数

  • 一家人就要整整齐齐,本人挺喜欢的两个函数
    upper官方文档
    lower官文
str="Zdn,FIGHTing!"
str_up=str.upper()
str_low=str.lower()
print("str_up :"+str_up)
print("str_low :"+str_low)

#运行结果如下:
#str_up :ZDN,FIGHTING!
#str_low :zdn,fighting!

-6.2isX()判断函数(感觉用的不多,但是用的好就挺妙的)

  • 判断是否是某某某,然后返回true或者false
str="Zdn,FIGHTing666!"
print(str.isupper())
print(str.islower())
print('ABC666'.isupper())#全大写
print('abc666'.islower())#全小写
print('ABC666'.isalpha())#全字母
print('ABC666'.isalnum())#全字母和数字
print('ABC666'.isdecimal())#全数字
print('   '.isspace())#只包含空格,制表符,换行
print('Abc66'.istitle())#大写字母开头,后面都是小写

#运行结果如下:
#False
#False
#True
#True
#False
#True
#False
#True
#True
实例:判断字符串是不是符合电话号码的规范
def isPhoneNumber(text):
    if len(text)!=12:
        return False
    for i in range(3):
        if not text[i].isdecimal():
            return False
        if text[3]!='-':
            return False
        for i in range(4,7):
            if not text[i].isdecimal():
                return False
            if text[7]!='-':
                return False
            for i in range(8,12):
                if not text[i].isdecimal():
                    return False
        return True
print((isPhoneNumber('415-555-4242')))
print(isPhoneNumber('abdc efg'))

-6.3startwith()&endwith()(检测是否以什么开头结尾)

  • 看字符串是不是以某某开头结尾的,返回true或者false,可以数字或者字符,区分大小写的
str="Zdn,FIGHTing666!"
print(str.startswith("zdn"))
print(str.endswith("6!"))

#运行结果如下:
#False
#True

-6.4join()&split()(用于列表和字符串的转换)

  • join():一般用于把列表还原成字符串
  • split():一般用于把字符串切分开成列表
lis=['mjq','dcx','syx','lyw','zzy','yhx','hjl']
str0=''.join(lis)
str1=' '.join(lis)
str2=','.join(lis)
str3='abc'.join(lis)
print(f"{str0}\n{str1}\n{str2}\n{str3}")
#运行结果如下:
#mjqdcxsyxlywzzyyhxhjl
#mjq dcx syx lyw zzy yhx hjl
#mjq,dcx,syx,lyw,zzy,yhx,hjl
#mjqabcdcxabcsyxabclywabczzyabcyhxabchjl
str='mjq dcx syx lyw zzy yhx hjl'
lis=str.split(' ')
print(lis)
#运行结果如下:
#['mjq', 'dcx', 'syx', 'lyw', 'zzy', 'yhx', 'hjl']

-6.5rjust()&ljust()& center()(填充字符串函数)

  • 函数说明:r在最右;l 在最左边;center是把字符串放在中间,往两边填充
  • 使用说明:默认是空格,(填充后总的字符串长度,“填充str只能一个字符”)–>注:如果width<=原字符串就不会填充
    rjust官文(注:right、left、center的官文都差不多,只是填充的位置不同而已)
print('Hello'.rjust(10,'o'))
print('Hello'.rjust(5,'o'))
print('hello'.center(10,'*'))
print('hello'.center(11,'*'))
#运行结果如下:
#oooooHello
#Hello
#**hello***
#***hello***

-6.6strip()&rstrip()&lstrip()(移除两端字符的函数)

  • 函数说明:strip()可以从头和尾删除指定的字符,直到碰到除指定之外的字符才会停止(这个有点不好,就是中间的指定字符没有办法删除,不能做查找删除)
  • 使用说明:默认删除两端的空格,(’str字符串,可以包含多个,没有顺序,是单个的‘)
    strip官文
str='Spam Spam Bacon Spam Eggs Spam Spam'
new=str.strip('ampS ')
print(new)

#运行结果如下
#Bacon Spam Eggs

-6.7pyperdip模块(复制粘贴涉及剪切版,目前还不知道有什么大用处)

  • 就是一个copy()和paste()没啥特别
import pyperdip
pyperdip.copy('hello')
print(pyperdip.psate())

-6.8find()&in(查找子串,返回索引或者bool)

  • 函数说明:find()是用来找某个子串在不在原字符串里,并返回第一个(只能找到第一个)位置的索引,找不到就返回-1。 in则直接判断在不在里面,返回bool值
  • 使用说明:(’要找的字符串‘,开始找的位置,结束找的位置)
    在这里插入图片描述
str='I wanna be a happy person,a positive people.'
print(str.find('a'))
print(str.find('a',10))
print(str.find('a',15,30))

#运行结果如下:
#3
#11
#26

-6.9正则表达式(import re)

正则表达式-学习文档–>菜鸟教程
~相关的函数挺多的~
再来一个吃灰的收藏
在这里插入图片描述

在这里插入图片描述

6.9.1pattern的写法
re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
  • 使用花括号{x}:代表*x次
re.compile(r'\d{3}-\d{3}-\d{4}')
  • 使用问号❓:()?括号里的内容可选,即匹配0次或者1次,即 =0 or 1
import re
obj=re.compile(r'Bat(wo)?man')
mo_1=obj.search("The Adventures of Batman")
mo_2=obj.search("The Adventures of Batwoman")
mo_3=obj.search("The Adventures of Batwowoman")
print(mo_1) #<re.Match object; span=(18, 24), match='Batman'>
print(mo_2) #<re.Match object; span=(18, 26), match='Batwoman'>
print(mo_3) #None
  • 使用星号✳:可以匹配多次,即 >=0
import re
obj=re.compile(r'Bat(wo)*man')
mo_1=obj.search("The Adventures of Batman")
mo_2=obj.search("The Adventures of Batwoman")
mo_3=obj.search("The Adventures of Batwowoman")
print(mo_1)#<re.Match object; span=(18, 24), match='Batman'>
print(mo_2)#<re.Match object; span=(18, 26), match='Batwoman'>
print(mo_3)#<re.Match object; span=(18, 28), match='Batwowoman'>
  • 使用加号➕:至少匹配一次,即 >=1
import re
obj=re.compile(r'Bat(wo)+man')
mo_1=obj.search("The Adventures of Batman")
mo_2=obj.search("The Adventures of Batwoman")
mo_3=obj.search("The Adventures of Batwowoman")
print(mo_1)#None
print(mo_2)#<re.Match object; span=(18, 26), match='Batwoman'>
print(mo_3)#<re.Match object; span=(18, 28), match='Batwowoman'>
  • 使用 (.) 和 (.+): (.)代表1个任意字符;(.+)代表 >=1个字符,此处省略一万个字哈哈~
import re
obj=re.compile(r'<h1>(.+)<h1>')
mo=obj.findall('<html><body><h1>helloworld<h1></body></html>')#<>没有任何意义,至少字符
print(mo)

#运行结果如下:
#['helloworld']
6.9.2对于输出格式的处理
  • group()函数

因为经过某些函数(如search)正常情况不做处理直接输出的话,会直接返回一大串长东西,(不过像findall这种返回列表的就不用处理),比如:<re.Match object; span=(18, 28), match='Batwowoman'>,所以我们要结合group()

import re
obj=re.compile(r'Batman|Tina Fey')
mo=obj.search('Batman and  Tina Fey')
print(mo.group())

#运行结果如下:
#Batman
6.9.3compile()
  • 函数说明: 中文意思为编译,正则表达是需要通过re.complie()函数来构造,就是把你要匹配的格式(a regular expression pattern)转化成 a regular expression object正则表达对象)–>(在我看来,就是把你要的长大概某个样的东西编译成正则表达式能看懂的格式样子吧,虽然长啥样我也不知道)

  • 使用说明:obj = re.compile(长某个样的东西,用要求的格式表达哈~)(注:obj就是可以用来.函数()的对象

  • 划重点说人话其实就是如果你不用compile把你的pattern变成object再用函数,就要在用函数时的第一个参数加上你的pattern,所以如果这个pattern用到的次数比较多,你就可以先compile它成一个object

在这里插入图片描述在这里插入图片描述

6.9.4search()
  • 函数说明:用来找第一个匹配的obj,返回一长串内容,包括索引位置的跨度+匹配的成功的第一个实例,如果想输出知道的一部分内容找到可以搭配group()一起食用;如果没有找到就返回None

  • 使用说明:obj.search(str[,pos[,endpos]])或者search(pattern,str,pos,endpos)这个怎么看呢?我来教你,可以看到()里有3个parameter,[]是可出现可不出现的,上式有两个[],就是括号里可以有单独str,也可以str,pos两个,也可以三个str是需要从里面找 obj 的string内容,the characters from pos to endpos - 1 will be searched for a match
    :第一个的obj是上面compile后的对象;如果没有compile就用第二个;查找范围是老规矩[pos,endpos)左闭右开

import re
str='Callmeat415-555-1011 tomorrow.415-555-9999 ismyoffice.'
exa=re.compile(r'((\d\d\d)-(\d\d\d-\d\d\d\d))')
match=exa.search(str)
print(match)

#运行结果如下:
#<re.Match object; span=(8, 20), match='415-555-1011'>
6.9.5findall()
  • 函数说明:找所有和obj匹配成功的实例,返回以列表的形式;如果没找返回空列表
  • 使用说明:obj.findall(str[,pos[,endpos]])或者findall(pattern,str,pos,endpos)
import re
str='Callmeat415-555-1011 tomorrow.415-555-9999 ismyoffice.'
exa=re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
match=exa.findall(str)
print(match)
exa=re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')#括号可以进行切分,结合输出看
match=exa.findall(str)
print(match)

#运行结果如下:
#['415-555-1011', '415-555-9999']
#[('415', '555-1011'), ('415', '555-9999')]

python第三方库查找官文

常用功能的第三方库(转载)
PyPi第三方库官方

  • 16
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值