Python字符串常用方法以及其应用场景详解

目录

前言

字符串作为一种重要的Python基本数据类型,在数据处理中发挥着不可或缺的作用,如果对它的方法能够灵活使用,能够达到事半功倍的效果。下面我们选取一些常用的方法,简述其应用场景。

一、最大化最小化方法

字符串的最大化方法upper()和最小化方法lower()可以将字符串全部转换为大写和小写。在数据处理分析过程中,如果涉及到字符串的比较和统计,尤其涉及到英文的,一般需要将字符串全部转化小写再进行比较统计,否则可能会不准。

比如根据用户的输入,决定接下来的程序是否执行,如果用户输入n则不执行,为了让程序设计的更加友好,需要考虑用户可能输入N的情况,该问题可以通过lower()或者upper()来解决。

>>> choice = input(\'是否继续执行程序,输入n或N则结束:\')
是否继续执行程序,输入n或N则结束:N
>>> if choice == \'n\'or choice == \'N\':  # 常规处理方式
	      print(\'程序结束\')
>>> if choice.lower() == \'n\':  #  推荐用该方法处理
	      print(\'程序结束\')

比如现在通过分词工具,已经把一段英文分词单词的列表,现在要统计“when”出现的次数,一般需要再统计之前将字符串全部最小化下。

>>> words = [\'When\', \'you\', \'fall\', \'stand\', \'up.\', \'And\', \'when\', \'you\', \'break\', \'stand\', \'tough\', \'And\', \'when\', \'they\', \'say\', \'you\', \'can\'t,\', \'you\', \'say\', \'I\', \'can\', \'I\', \'can\']
>>> count = 0
>>> sta_word = \'when\'
>>> for word in words:
	    if word.lower() == sta_word:
		    count += 1
>>> print(\'{}出现了{}次\'.format(\'when\', count))
when出现了3次

二、统计次数方法

统计次数的count()方法可以快速统计字符串中某个子串出现的次数,但这个方法在列表数据类型中应用较多,在字符串中应用很少,使用不当容易造成不易察觉的错误。

比如统计“帽子和服装如何搭配才好看”这句话中“和服”出现的次数,虽然出现了“和服”,但不是想要统计的结果,对于英文中很多单词有多种时态,更是如此。对于文本中词频的统计,一般需要先进行分词处理,英文可能还需要进行词形还原处理,然后再统计词频。

>>> \"帽子和服装如何搭配才好看\".count(\"和服\")
1
>>> import jieba
>>> words = jieba.lcut(\"帽子和服装如何搭配才好看\")
>>> words
[\'帽子\',\'和\',\'服装\',\'如何\',\'搭配\',\'才\',\'好看\']
>>> words.count(\"和服\") # 分词后再统计
0

三、去掉左右侧字符方法

在做文本处理任务时,对于网络上爬取或者其他渠道获取的数据信息,经常会存在“噪声”,即会有一些没有实际意义的字符,干扰文本的格式和信息的提取,此时strip()lstrip()rstrip()方法就可以帮助删除掉字符串头部和尾部的指定字符。当字符没有被指定时,默认去除空格或换行符。lstrip()代表删除字符串左侧(即头部)出现的指定字符,rstrip()代表删除字符串右侧(即尾部)出现的指定字符。下面通过几个例子来说明。

>>> temp_str = \"  tomorrow is another day \"
>>> temp_str.strip()
\'tomorrow is another day\'
>>> temp_str = \"#  tomorrow is another day @\"
>>> temp_str.strip(\'#\')
\'  tomorrow is another day @\'
>>> temp_str.strip(\'# @\')
\'tomorrow is another day\'
>>> temp_str = \"#@  tomorrow is another day @\"
>>> temp_str.lstrip(\'@# \')
\'tomorrow is another day @\'

四、字符串分隔方法

当字符串具有特定的格式,或者需要处理的数据具有结构化特点,比如excel表格的数据、或者json格式的文件等,当提取其中的某一个或几个字段时,需要先对字符串进行分隔。split()方法以指定的分隔符为基准,将分隔后得到的字符串以数组类型返回,方便进行之后的操作。当没有指定分隔符时,默认以空格分隔。

>>> temp_str = \"Whatever is worth doing is worth doing well\"
>>> temp_str.split()
[\'Whatever\', \'is\', \'worth\', \'doing\', \'is\', \'worth\', \'doing\', \'well\']
>>> temp_str = \"tomorrow#is#another#day\"
>>> temp_str.split(\'#\')
[\'tomorrow\', \'is\', \'another\', \'day\']
>>> temp_str = ‘\"name\":\"Mike\",\"age\":18,\"sex\":\"male\",\"hair\":\"black\"\'
>>> temp_str.split(\',\')
[\'\"name\":\"Mike\"\', \'\"age\":18\', \'\"sex\":\"male\"\', \'\"hair\":\"black\"\']

五、字符串替换方法

字符串替换也是很常用的方法之一。例如发现有输入错误的时候,正确的要替换掉错误的,或者需要将一些没有意义的字符统一去除或者换成空格的时候,都可以考虑使用replace()方法。第三个参数为可选参数,表示替换的最大次数。

>>> temp_str = \"this is really interesting, and that is boring.\"
>>> temp_str.replace(\'is\',\'was\')
\'thwas was really interesting, and that was boring.\'
>>> temp_str.replace(\'is\',\'was\')
\'this was really interesting, and that was boring.\'
>>> temp_str = \'I really really really like you.\'
>>> temp_str.replace(\"really\",\"\",2)
\'I   really like you.\'

上例显示出,字符串中出现的所有is都被进行了替换,包括包含is的单词,这也是编程中需要考虑的问题。如果是英文字符串,可以考虑通过加上空格的方式来避免错误的替换,如第四行所示。

六、字符串拼接方法

字符串的拼接方法与其分隔方法可以看作是互逆操作,join()方法将序列中的元素以指定的字符连接,生成一个新的字符串。这个序列可以是字符串、元组、列表、字典等。

>>> seq = \'hello world\'
>>> \":\".join(seq)
\'h:e:l:l:o: :w:o:r:l:d\'
>>> seq = (\'Whatever\', \'is\', \'worth\', \'doing\', \'is\', \'worth\', \'doing\', \'well\')
>>> \"*\".join(seq)
\'Whatever*is*worth*doing*is*worth*doing*well\'
>>> seq = [\'Whatever\', \'is\', \'worth\', \'doing\', \'is\', \'worth\', \'doing\', \'well\']
>>> \" \".join(seq)
\'Whatever is worth doing is worth doing well\'
>>> seq = [\'\"name\":\"Mike\"\', \'\"age\":18\', \'\"sex\":\"male\"\', \'\"hair\":\"black\"\']
>>> \"#\".join(seq)
\'\"name\":\"Mike\"#\"age\":18#\"sex\":\"male\"#\"hair\":\"black\"\'

七、判断是否为数字的方法

isdigit()方法用于判断一个字符串是否全部都由数字组成,返回值为布尔值。如果字符串中存在小数点或者符号,也不能认为全都是数字,如下例所示:

>>> num = \"13579\"
>>> num.isdigit()
True
>>> num = \'1.0\'
>>> num.isdigit()
False
>>> num = \'-1\'
>>> num.isdigit()
False

八、判断是否为空格的方法

isspace()方法用于判断一个字符串是否全部都由空格组成,返回值为布尔值。要注意的是,空字符串返回False。如下例所示:

>>> t = \'\'
>>> t.isspace()
False
>>> t = \'  \'
>>> t.isspace()
True

九、判断前缀和后缀的方法

startswith()endswith()分别用于判断字符串的前缀和后缀,即它的开始部分和结尾部分,返回值为布尔值,后面有两个可选参数,相当于对字符串做一个切片后再判断前缀/后缀。如下例所示:

>>> temp_str = \"Whatever is worth doing is worth doing well\"
>>> temp_str.startswith(\"W\")
True
>>> temp_str.startswith(\"What\")
True
>>> temp_str.startswith(\'Whatever\',2)
False
>>> temp_str.endswith(\"well\",2)
True
>>> temp_str.endswith(\"we\",2,-2)
True

补充:更多Python字符串常用方法

a = \"hello world\"
# 字符串不能通过索引进行修改  name[0] = \'q\'
 
# 切片,查找字符串当中的一段值,[起始值:终止值:步长]不写步长默认是1
print(a[0:5:])
print(a[::-1])  # 步长负数倒过来走,不写起始值和终止值就走完全部
print(a[::1])
print(len(a))  # len方法获取字符串的长度
 
# in 和 not in :判断一个字符串是否在一个大的字符串中
# 返回值为布尔类型
print(\'hello\' in \'hello world\')
print(\'nihao\' not in \'hello world\')
 
# 字符串的增
print(\'nihao\', \'Python\')
print(\'nihao\' + \'Python\')
 
# format    前面的大括号写上数字代表着取后面括号里的索引位置
print(\'==============format================\')
print(\'my name is {}\'.format(100))
print(\'my name is {1},my age is {0}\'.format(\'dayv\', 18))
print(\'my name is {0},my age is {1}\'.format(\'dayv\', 18))
 
# join  把列表里的元素组成字符串
str1 = \'真正的勇士\'
str2 = \'敢于直面惨淡的人生\'
str3 = \'敢于正视淋漓的鲜血\'
print(\'\'.join([str1, str2, str3]))
# 前面的逗号表示用什么来隔开,列表中只能是字符串才能使用join方法
print(\',\'.join([str1, str2, str3]))
 
# 删   del
name1 = \'nihao\'
del name1  # 这就把这个变量删除了,在输出这个变量就会出错
 
# 改
# 字符串变大小写 upper , lower ,
name1 = \'abc\'
print(\'大写:\' + name1.upper())
print(name1.lower())
 
# capitalize  将第一个字母转换成大写
print(name1.capitalize())
 
# 将每个单词的首字母大写  title
name2 = \'hello world\'
print(\'每个单词首字母大写:\' + name2.title())
print(\'原name2的值\' + name2)
 
# 将字符串切分成列表  默认空格为字符切分  split
name1 = \'a b    cd e\'
print(name1.split())
# 括号里写什么就用什么切分                !!!!!!!!!!!!!!!!!!!!
name1 = \'a1b1cd1e\'
print(\"自己配置用什么东西切分\", name1.split(\'1\'))  # 返回的是列表
# rsplit(\'指定用什么切片\', 切几次),反过来切
print(\'切片倒过来切使用rsplit\', name1.rsplit(\'1\', 1))  # 倒过来切一个元素
# 替换replace(被替换的字符,替换的字符,个数)     !!!!!!!!!!!!!!
print(name1.replace(\'1\', \'0\'))
print(name1.replace(\'1\', \'0\', 1))  # 个数是从左往右的顺序替换
aaaaa = \' sdf   kkf  k k   \'
print(\'使用替换去除字符串中的全部空格\', aaaaa.replace(\" \", \'\'))
 
# strip  除去字符串两边的空格,中间的不会管
name1 = \'        ni h ao     \'
print(name1.strip())
 
# 查
# find  index
# 查找字符串在大字符串的那个索引位置(起始索引)
name1 = \'PythonPythonPython\'
print(\"使用find查找的索引位置\", name1.find(\'on\'))
# 找不到会返回-1
print(\"使用index查找的索引位置:\", name1.index(\'on\'))
# index方法找不到会报错
 
# count  统计一个字符串在大字符串里面出现的次数
print(name1.count(\'qi\'))
 
# 判断一个字符串里的数据是不是都是数字  isdigit   返回布尔值
num = \'156465\'
print(num.isdigit())
# 判断一个字符串里的数据是不是都是字母   isalpha
num = \'ksdjflks\'
print(num.isalpha())
 
# 比较后面一个元素是否是前面一个元素的开头,startswith
# 比较后面一个元素是否是前面一个元素的结尾  endswith
mm = \'Python nihao\'
print(mm.startswith(\'Pyth\'))
print(mm.endswith(\'Pytho\'))
 
# 判断字符串是否全是大写isupper   是否全是小写islower
 
# 转义字符 \\n换行   \\t
print(\'hello \\nworld\')
print(\'z\\tiyu\')
print(\'Pyth \\t on\')
print(\'Python123\')
# 反转义
print(r\'zhai \\t dada\')  # 加r
print(\'zhai \\\\t dada\')  # 或者写两个斜杠
 
# 控制字符串的输入字数
print(\'123456\'[:5])  # 只会输入前五个数

总结

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容