Python极简笔记(三)---字符串

一、增

1.1 基本操作

  • 字符串:基本操作函数同list。
  • 代码示例
    # 赋值
    str1 = 'this is the line'
    # 运算
    str2 =str1[:5] + 'was' + str1[7:]	
    >>>this was the line
    # 判断相等:建议常量写前边
    if "str" == str1: print("equal")
    

1.2 格式化赋值

  • format示例
    # 占位符用字符串:也可为字符串变量
    In [1]: "第一个:{0},第二个:{1}".format('first', 'second')
    Out[1]: '第一个:first,第二个:second'
    
    # 占位符用字典
    In [2]: d = dict(first='fir', second='sec')
    In [2]: "{second} is sec, {first} is fir".format(**d)
    Out[2]: 'sec is sec, fir is fir'
    
    # 格式化浮点数:宽度随字符串
    In [3]: "{:.2f}".format(3.1415)
    Out[3]: '3.14'
    # 默认右对齐
    In [4]: "{:10.2f}".format(3.1415)
    Out[4]: '      3.14'
    # 居中对齐
    In [5]: "{:^10.2f}".format(3.1415)
    Out[5]: '   3.14   '
    # 左对齐
    In [6]: "{:<10.2f}".format(3.1415)
    Out[6]: '3.14      '
    # 设定填充符
    In [7]: "{:_^10.2f}".format(3.1415)
    Out[7]: '___3.14___'
    # 数值逗号分隔
    In [8]: "{:,}".format(123456789)
    Out[8]: '123,456,789'
    

二、改

2.1 大小切换

  • 代码示例
    # 操作字符串
    In [1]: str1 = 'this is the line'
    # 首字母大写
    In [2]: str1.capitalize()
    Out[2]: 'This is the line'
    # 全大写
    In [3]: str1.upper()
    Out[3]: 'THIS IS THE LINE'
    # 全小写
    In [4]: str1.lower()
    Out[4]: 'this is the line'
    

2.2 对齐式填充

  • 代码示例
    # 操作字符串
    In [1]: str2 = "this"
    # 返回新字符串:居中对齐,总共8个字符,填充字符
    # 也可以单参,用空格填充,2、3均同
    In [2]: str2.center(8, '-')
    Out[2]: '--this--'
    # 返回新字符串:右对齐,总共8个字符
    In [3]: str2.rjust(8)
    Out[3]: '    this'
    # 返回新字符串:左对齐,总共8个字符
    In [4]: str2.ljust(8)
    Out[4]: 'this    '
    # 去除两侧空格:存储用户输入前的清理工作
    # 还有lstrip()和rstrip()
    In [5]: str3 = " t h i s "
    In [6]: str3.strip()
    Out[6]: 't h i s'
    

    用处:常与print函数一起使用

2.3 切片方法

  • 代码示例
    In [1]: str_path = '/root/chuck.sh'
    # split('指定原字符串的分隔字符',分区段数)
    # 可以用元组接收 fir,sec,thd = str_path.split('/',3)
    In [2]: str_path.split('/', 3)
    Out[2]: ['', 'root', 'chuck.sh']
    
    # 拼接可迭代对象
    In [3]: '/'.join(['', fir, sec, thd])
    Out[4]: '/root/chuck.sh'
    

2.4 字符串替换

  • 静态替换replace
    # 字符串无差别替换
    In [1]: str1 = "this this this"
    
    In [2]: str1.replace("is", "was")
    Out[2]: 'thwas thwas thwas'
    
  • 动态替换re模块
    # 看完3.3节后再来:注意原字符串不会被修改
    In [1]: import re
    
    In [2]: str1 = "我的手机号是:123456789"
    # sub方法:正则语句,替换的字符串,输入待处理字符串
    In [3]: re.sub(r"/d", "*", str1)
    Out[3]: '我的手机号是:123456789'
    # 分别替换:每个数字都分别替换为*
    In [4]: re.sub(r"[0-9]", "*", str1)
    Out[4]: '我的手机号是:*********'
    # 合并替换:将连片数字体会为一个*
    In [5]: re.sub(r"\d+", "*", str1)
    Out[5]: '我的手机号是:*'
    

三、查

3.1 基础判断

  • 基础判断函数(返回布尔值)
    写法功能
    startswith(‘字符串’)判断开头结尾字符串
    startswith(‘子字符串’,起始位,终止位)进阶"this is".startswith('hi',1,2)返回True
    或者"this is".startswith('is',1)返回True
    endswith用法同上
    isspace()只含空字符:'\t', ' ', ' \n'
    isalnum()只含数字和字母,如‘a1’
    isalpha()只含字母
    isdigit()只含狭义数字,即:“0-9
    isnumeric()只含广义数字:Unicode 数字(\u0030),全角数字(双字节),罗马数字(),汉字数字(
    isdecimal()只含十进制整数:'101'
    istitle()仅首字母大写:'Title',不行TiTle

3.2 查子字符串

  • 查找子字符串位置
    In [1]: str1 = "abcdefgh"
    # 返回值:若存在则返回索引值
    In [2]: str1.find('bc')
    Out[2]: 1
    # 返回值:若不存在则返回-1
    In [3]: str1.find('bd')
    Out[3]: -1
    # 指定起始位置查找
    In [4]: str1.find('ef', 4, 7)
    Out[4]: 4
    
  • 计算子字符串出现次数
    In [1]: str1 = "aabbaabb"
    
    In [2]: str1.count('ab')
    Out[2]: 2
    

3.3 正则查找

3.3.1 通配符表

  • 正则通配符

    格式描述格式描述
    ^匹配字符串开头$匹配字符串末尾
    .任意字符,除了换行符a?0、1个a
    a+1~无穷大个aa*0~无穷大个a
    [amk]匹配 ‘a’,‘m’或’k’ ,[0-2]为0、1、2[^amk]匹配非 ‘a’,‘m’,’k’的字符
    [0-1]{3}精确匹配n个表达式,000、111[0-1]{2,3}匹配00、11、000、111
  • 分组匹配

    格式描述
    (表达式)分组匹配,与?、*、+一块用
    (表达式1)|(表达式2)表达式的或语句
    ([a-z])([a-z])\2\1匹配:abba、cddc、mnnm这样的,数字代表组序号
  • 扩展正则通配符

    格式描述
    \d匹配任意数字,等价[0-9],\D:匹配\d
    \w匹配包括下划线的任何单词字符,等价:[A-Za-z0-9_]_\S:匹配\w
    \s匹配任意空白字符,\S:匹配\s

3.3.2 re模块使用

  • 正则查找findall
    In [1]: import re
       ...: str1 = "https://editor.csdn.net/md/?articleId=105421293#43__140"
       # 常规匹配:r代表字符串按纯字符串考虑,不考虑转义
       ...: re.findall(r'\d+', str1)
    # 将匹配到的字符串以列表形式列出
    Out[1]: ['105421293', '43', '140']
    
  • 正则替换sbu
    In [1]: str1 = "https://editor.csdn.net/md/?articleId=105421293#43__140"
    # 参数:正则表达式、替换成的字符串、待操作字符串
    In [2]: re.sub(r'[0-9]+', '', str1)
    # 返回:替换后的字符串,也可以用str1接收,直接覆盖原字符串变量
    Out[2]: 'https://editor.csdn.net/md/?articleId=#__'
    
  • 精准正则提取方法match
    In [1]: import re
    
    In [2]: str1 = "https://editor.csdn.net/md/?articleId=105421293#43__140"
    # 贪婪匹配:* 代表0~无穷大,即最后一个 * 最少取0个,+最少取1个,
    # 		  剩下的都被第一个恶霸 * 贪婪的拿走
    # 返回值:re.match封装对象,<re.Match object; >
    In [3]: result = re.match(r"https.*(\d+).*$", str1)
    # span方法:返回匹配的字符串起终索引值
    In [4]: result.span()
    Out[4]: (0, 55)
    # group方法:默认参数为0,返回匹配的字符串段,这里全字符是因为规则^$决定的
    # 未匹配到会返回none
    In [5]: result.group()
    Out[5]: 'https://editor.csdn.net/md/?articleId=105421293#43__140'
    # 提取小括号内的匹配字符串,贪婪匹配导致\d+最少匹配一个字符,其他都被恶霸*拿走了
    # 通常加后面判断,因为如果未匹配到,会抛出异常
    In [6]: result.group(1) if res else None
    Out[6]: '0'
    # 非贪婪匹配:在*、?、+、{m,n}后面加上?,使贪婪变成非贪婪,
    # 			即让这几个尽量匹配最少次数,第二个*接替变成贪婪匹配的恶霸
    In [7]: result = re.match(r"https.*?(\d+).*$", str1)
    # 第一个*不允许批评任何\d字符,+ 执行贪婪匹配
    # 通常加后面判断,因为如果未匹配到,会抛出异常
    In [8]: result.group(1) if res else None
    Out[8]: '105421293'
    

回到总目录

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值