Python处理字符串的常用函数实例总结

目录
  • 前言
  • 字符串都有哪些操作?
  • 第一类 判断识别字符串
  • 第二类 字符串编辑的操作
  • 第三类:字符串跟字节串的互转
  • 总结

前言

今天我们说了字符串的基础,格式化,这次我们讲解字符串的常用函数,不要错过!

前两篇都在本文同个专栏,欢迎关注。下面开始讲解。

字符串都有哪些操作?

实际开发都有这些需求:

第一大类:判断识别字符串

  • 判断字符串属于那种字面类型(数字,全字母,其他)
  • 判断字符串包含某些结构(数字大写,局部子串,子串出现频次等)

第二类:字符串编辑的操作(生成新字符串)

  • 字符串的替换/合并/填充等
  • 字典替换,填充0值,清空操作等

第三类:字符串跟字节串的互转。

这类操作通常发生在数据跨程序/跨服务器传输,我们传输bytes,然后获取转string类型。

第一类 判断识别字符串

学委准备了下面的代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/10/30 10:13 上午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷学委
# @XueWeiTag: CodingDemo
# @File : string_funs_cat1.py
# @Project : hello
import sys

slogan = "keep studying, keep coding, I am Levin"

# 判断结构
print("算某个子串出现数次: slogan.count('keep') = ", slogan.count('keep'))
print("找某个子串首次出现的下标: slogan.find('keep') = ", slogan.find('keep'))
print("找某个子串最后出现的下标: slogan.rfind('keep') = ", slogan.rfind('keep'))
print("找某个子串下标: slogan.index('keep') = ", slogan.index('keep'))
print("找某个子串下标: slogan.rindex('keep') = ", slogan.rindex('keep'))
print("是否'keep'开头的字符串: slogan.startswith('keep') = ", slogan.startswith('keep'))
print("是否'keep'结束的字符串: slogan.endswith('keep') = ", slogan.endswith('keep'))

# 字符串属性相关
print("字符串长度: len(slogan) = ", len(slogan))
print("字符串是否都是空格: slogan.isspace() = ", slogan.isspace())
print("字符串是否大写: slogan.isupper() = ", slogan.isupper())
print("字符串是否小写: slogan.islower() = ", slogan.islower())
print("字符串是否为每个词首字母都大写: slogan.istitle() = ", slogan.istitle())

# 判断字符串数据类型
print("字符串是否全为字母: slogan.isalpha() = ", slogan.isalpha())
print("字符串是否全为数字: slogan.isalnum() = ", slogan.isalnum())
print("字符串是否数字: slogan.isnumeric() = ", slogan.isnumeric())
print("字符串是否浮点数: slogan.isdecimal() = ", slogan.isdecimal())
print("字符串是否为空格串: slogan.isspace() = ", slogan.isspace())

读者可以直接复制运行代码,学委补充了运行效果图:

第二类 字符串编辑的操作

下面学委准备了一些代码展示:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/10/30 10:13 上午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷学委
# @XueWeiTag: CodingDemo
# @File : string_funs_cat2.py
# @Project : hello
import sys

slogan = "keep studying, keep coding, I am Levin"

print("首字母大写: slogan.capitalize() = ", slogan.capitalize())
print("全部字母大写: slogan.upper() = ", slogan.upper())
print("全部字母小写: slogan.lower() = ", slogan.lower())
print("转为首字母都大写(标题风格): slogan.title() = ", slogan.title())
print("大小写逆转: slogan.swapcase() = ", slogan.swapcase())

table = slogan.maketrans({"e": "5"})
print("字符串替换表: slogan.translate(table) = ", slogan.translate(table))

# 字符串替换,合并,填充等
print("替换tabs为n个空格: 'hello\t学委'.expandtabs(4) = '", "hello\t学委".expandtabs(4))
print("左子串来串联传入的列表: ' '.join(slogan) = '", " ".join(slogan))
print("替换子串: ' '.replace(first, second) = '", slogan.replace("e", "11"))
print("填充0值: slogan.rzfill(2)= '", slogan.zfill(50))
print("填充#值: slogan.rjust(50,"#")= '", slogan.rjust(50,"#"))
print("填充#值: slogan.ljust(50,"#")= '", slogan.ljust(50,"#"))
print("移除首尾空格: slogan.strip()= '", slogan.strip())

data = slogan.split("e")
print("split slogan into data= ", data)

运行效果如下:

第三类:字符串跟字节串的互转

下面学委准备了一些代码展示:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/10/30 10:13 上午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷学委
# @XueWeiTag: CodingDemo
# @File : string_funs_cat3.py
# @Project : hello
import sys

slogan = "keep studying, keep coding, I am Levin"
bytes = slogan.encode("utf-8")
print("type of encoded string = ", type(bytes))
# 注意python的string类型没有decode函数,该函数属于bytes类型对象特有!!!
print("type of decoded byte = ", type(bytes.decode("utf-8")))
print("type of decoded byte = ", bytes.decode("utf-8"))

运行效果如下:

总结

其实学委还漏了几个函数,但是不想介绍它们了。

学习编程不是去记忆,但是也并非啥都不看都靠感觉。

我喜欢下面这句话:

读书破万卷,下笔如有神!

精心准备的代码,读者运行一下,自己感悟!(注释写的很清楚了)

到此这篇关于Python处理字符串的常用函数的文章就介绍到这了,更多相关Python处理字符串函数内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 浅析python 内置字符串处理函数的使用方法

    一.lower():将大写字母全部转为小写字母.如: 复制代码 代码如下: name='G'b=name.lower() 二.title"":将字符串转化为标题,即所有单词的首字母大写,其他字母小写.使用方法同lower() 三.replace:返回某字符串的所有匹配项均被替换之后得到的字符串. 复制代码 代码如下: 'This is a test'.replace('is','are') 四.split:将字符串分割成序列 复制代码 代码如下: '1+2+3+4+5'.split('

  • Python字符串处理函数简明总结

    返回被去除指定字符的字符串 默认去除空白字符 删除首尾字符:str.strip([char]) 删除首字符:str.lstrip([char]) 删除尾字符str.strip([char]) 判断是否匹配首末字符 匹配成功返回True,否则返回False 匹配首字符:str.startswith(char[, start[, end]]) 匹配末字符:str.endswith(char[, start[, end]]) 查找字符,找到返回字符位置,否则返回-1 从字符串开头查找str.find(

  • Python内置的字符串处理函数详细整理(覆盖日常所用)

    str='python String function' 生成字符串变量str='python String function' 字符串长度获取:len(str) 例:print '%s length=%d' % (str,len(str)) 字母处理 全部大写:str.upper() 全部小写:str.lower() 大小写互换:str.swapcase() 首字母大写,其余小写:str.capitalize() 首字母大写:str.title() print '%s lower=%s' %

  • python常见字符串处理函数与用法汇总

    本文实例讲述了python常见字符串处理函数与用法.分享给大家供大家参考,具体如下: 1.find 作用:在一个较长字符串中查找子串.返回子串所在位置的最左端索引,如果没有找到则返回-1.如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1. 用法:string.find() 实例: a = ' i am a boy with no money ' print a.find('a') 输出结果: 5 print a.fin

  • Python内置的字符串处理函数整理

    str='python String function' 生成字符串变量str='python String function' 字符串长度获取:len(str)例:print '%s length=%d' % (str,len(str)) 字母处理全部大写:str.upper()全部小写:str.lower()大小写互换:str.swapcase()首字母大写,其余小写:str.capitalize()首字母大写:str.title()print '%s lower=%s' % (str,st

  • Python处理字符串的常用函数实例总结

    目录 前言 字符串都有哪些操作? 第一类 判断识别字符串 第二类 字符串编辑的操作 第三类:字符串跟字节串的互转 总结 前言 今天我们说了字符串的基础,格式化,这次我们讲解字符串的常用函数,不要错过! 前两篇都在本文同个专栏,欢迎关注.下面开始讲解. 字符串都有哪些操作? 实际开发都有这些需求: 第一大类:判断识别字符串 判断字符串属于那种字面类型(数字,全字母,其他) 判断字符串包含某些结构(数字大写,局部子串,子串出现频次等) 第二类:字符串编辑的操作(生成新字符串) 字符串的替换/合并/填

  • python清除字符串中间空格的实例讲解

    1.使用字符串函数replace >>> a = 'hello world' >>> a.replace(' ', '') 'helloworld' 看上这种方法真的是很笨. 2.使用字符串函数split >>> a = ''.join(a.split()) >>> print(a) helloworld 3.使用正则表达式 >>> import re >>> strinfo = re.compil

  • python中强大的format函数实例详解

    python中format函数用于字符串的格式化 自python2.6开始,新增了一种格式化字符串的函数str.format(),此函数可以快速处理各种字符串. 语法 它通过{}和:来代替%. 请看下面的示例,基本上总结了format函数在python的中所有用法 #通过位置 print '{0},{1}'.format('chuhao',20) print '{},{}'.format('chuhao',20) print '{1},{0},{1}'.format('chuhao',20) #

  • Python数据分析之NumPy常用函数使用详解

    目录 文件读入 1.保存或创建新文件 2.读取csv文件的函数loadtxt 3.常见的函数 4.股票的收益率等 5.对数收益与波动率 6.日期分析 总结 本篇我们将以分析历史股价为例,介绍怎样从文件中载入数据,以及怎样使用NumPy的基本数学和统计分析函数.学习读写文件的方法,并尝试函数式编程和NumPy线性代数运算,来学习NumPy的常用函数. 文件读入 读写文件是数据分析的一项基本技能 CSV(Comma-Separated Value,逗号分隔值)格式是一种常见的文件格式.通常,数据库的

  • Python入门之三角函数sin()函数实例详解

    描述 sin()返回的x弧度的正弦值. 语法 以下是sin()方法的语法: importmath math.sin(x) 注意:sin()是不能直接访问的,需要导入math模块,然后通过math静态对象调用该方法. 参数 x--一个数值. 返回值 返回的x弧度的正弦值,数值在-1到1之间. 实例 以下展示了使用sin()方法的实例: #!/usr/bin/python import math print "sin(3) : ", math.sin(3) print "sin(

  • Python入门之三角函数tan()函数实例详解

    描述 tan() 返回x弧度的正弦值. 语法 以下是 tan() 方法的语法: import math math.tan(x) 注意:tan()是不能直接访问的,需要导入 math 模块,然后通过 math 静态对象调用该方法. 参数 x -- 一个数值. 返回值 返回x弧度的正弦值,数值在 -1 到 1 之间. 实例 以下展示了使用 tan() 方法的实例: #!/usr/bin/python import math print "tan(3) : ", math.tan(3) pr

  • python清除字符串前后空格函数的方法

    python有时候需要清除字符串前后空格,而字符本身的空格不需要清除掉,那就不能用正则re.sub来实现. 这时用到strip()函数 用法: str = ' 2014-04-21 14:10:18 ' str2 = str.strip() str3 = re.sub(' ','',str) print str2 print str3 结果如下: >2014-04-21 14:10:18 >2014-04-2114:10:18 以上这篇python清除字符串前后空格函数的方法就是小编分享给大家

  • python中字符串最常用的十三个处理操作记录

    前言 博主学习python有个几年了,对于python的掌握越来越深,很多时候,希望自己能掌握python越来越多的知识,但是,也意识很多时候熟练基础的东西,比了解更多的知识更重要. 今天,我们来讲讲python字符串处理 首先,我们先定义两个字符串,然后后面我们会对其进行一系列操作示范 str1="sadf AVD" str2="JIK dojfa kldfj" 1.把小写字母都转化为大写 print(str2.upper()) print(str1.upper(

  • python中os.path.join()函数实例用法

    1.说明 拼接文件路径,可以有多个参数. 2.语法 os.path.join(path1,path2,*) path1 初始路径. path2 需要拼接在其后的路径.初始路径文件夹下的文件或文件夹.可以有多个需要拼接的参数,依次拼接. 3.注意 如果拼接在后的参数中含有'\'开头的参数,将从'\'开头的参数开始,前面的参数均将失效,并且路径将从对应磁盘的根目录开始. 4.实例 >>> import os >>> path='D:\dataset' >>>

  • python copy模块中的函数实例用法

    1.copy.copy()函数可用于复制列表或字典等可变值,复制后的列表和原列表是两个独立的列表. import copy origin = [1,2,3] new = copy.copy(origin) new[0] = 0 print("origin = ",origin) print("new = ",new) 2.如果要复制的列表中有列表,则使用deepcopy()函数完全复制. import copy origin =[[1,2,3],['a','b','

随机推荐