本站内容均来自兴趣收集,如不慎侵害的您的相关权益,请留言告知,我们将尽快删除.谢谢.
字符串作为一种重要的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
Be First to Comment