Python基础(二):字符串方法总结

是小鱼呀·2022-02-13 19:11·85 次阅读

Python基础(二):字符串方法总结

字符串方法

字符串拼接#

直接通过(+)操作拼接#

Copy
print('hello'+' '+'world'+'!') > hello world!

使用这种方式进行字符串连接的操作效率低下,因为python中使用 + 拼接两个字符串时会生成一个新的字符串,生成新的字符串就需要重新申请内存,当拼接字符串较多时自然会影响效率

通过str.join()方法拼接#

Copy
str_list = ['hello', ' ', 'world', '!'] print(''.join(str_list)) > hello world!

这种方式一般用在列表转字符串,''.join其中''可以是空字符,也可以是任意字符,当时任意字符时,列表中字符串会被该字符隔开。

Copy
str_list = ['hello', ' ', 'world', '!'] print(':'.join(str_list)) > hello: :world:!

通过str.format()方法拼接#

Copy
print('{} {}!'.format('hello', 'world')) > hello world!

通过这种方式拼接字符串需要注意的是字符串中{}的数量要和format方法参数数量一致,否则会报错

通过(%)操作符拼接#

Copy
print('测试 %s' % 'Hello') print('测试 %s 测试 %s' % ('hello', 'world')) > 测试 Hello > 测试 hello 测试 world

也用于格式化字符串,%s表示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以省略。

常见的占位符:

占位符 替换内容
%d 整数
%f 浮点数
%s 字符串
%x 十六进制整数

如果不确定用什么,%s永远起作用,它会把任何数据类型转换为字符串
有时候字符串里面的%是一个普通字符,就需要转义,用%%来表示一个%:

Copy
print('growth rate: %d %%' % 7)

通过()多行拼接#

Copy
print( 'hello' ' ' 'world' '!' ) > hello world!

python遇到未闭合的小括号,自动将多行拼接为一行。

通过string 模块中的Template对象拼接#

Copy
from string import Template s = Template('${s1} ${s2}') t = s.safe_substitute(s1='hello', s2='world') print(t) > hello world

Template的实现方式是首先通过Template初始化一个字符串。这些字符串中包含了一个个key。通过调用substitute或safe_subsititute,将key值与方法中传递过来的参数对应上,从而实现在指定的位置导入字符串。这种方式的好处是不需要担心参数不一致引发异常

通过F-strings拼接#

Copy
s1 = 'hello' s2 = 'world' s3 = f'{s1} {s2}!' print(s3) > hello world!

在python3.6.2版本中,PEP 498 提出一种新型字符串格式化机制,被称为“字符串插值”或者更常见的一种称呼是F-strings,F-strings提供了一种明确且方便的方式将python表达式嵌入到字符串中来进行格式化
而且F-strings的运行速度很快,比%-string和str.format()这两种格式化方法都快得多

在F-strings中我们也可以执行函数:

Copy
def power(x): return x * x x = 5 print(f'{x}*{x}={power(x)}')

字符串的格式化#

通过(%)操作符#

Copy
print('测试 %s' % 'Hello') print('测试 %s 测试 %s' % ('hello', 'world')) > 测试 Hello > 测试 hello 测试 world

也用于格式化字符串,%s表示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以省略。

常见的占位符:

占位符 替换内容
%d 整数
%f 浮点数
%s 字符串
%x 十六进制整数

如果不确定用什么,%s永远起作用,它会把任何数据类型转换为字符串
有时候字符串里面的%是一个普通字符,就需要转义,用%%来表示一个%:

Copy
print('growth rate: %d %%' % 7)

通过format()方法#

Copy
print('Hello, {0}, 成绩提升了 {1:.1f}%'.format('小明', 17.125))

使用字符串的format()方法,它会用传入的参数依次替换字符串内的占位符{0}{1}……,不过这种方式写起来比%要麻烦得多:

字符串其他方法#

字符串替换#

Copy
str.replace(old, new[, max])
  • old -- 将被替换的子字符串。
  • new -- 新字符串,用于替换old子字符串。
  • max -- 可选字符串, 替换不超过 max 次

返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。

Copy
s = 'abc' print(s.replace('abc', 'e', 1)) > e

find 、index、rfind、rindex#

  • find:检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。

  • index:检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。

  • rfind:类似于find()函数,只不过是从字符串右边开始查找。

  • rindex:类似于index()函数,只不过是从字符串右边开始查找。

Copy
str1.find(str2, beg=0, end=len(str1)) str1.index(str2, beg=0, end=len(str1))
  • str1 -- 指定检索的字符串
  • str2 -- 要查找的子字符串
  • beg -- 开始索引,默认为0。
  • end -- 结束索引,默认为字符串的长度。
Copy
str1 = '0123456' str2 = '23' print(str1.find(str2)) print(str1.find(str2, 0)) print(str1.find(str2, 3)) print(str1.find(str2, 0, len(str1))) > 2 > 2 > -1 > 2

用index方法,字符串中不包含要查找的子字符串

Copy
str1 = '0123456' str2 = '23' print(str1.index(str2,3)) > Traceback (most recent call last): > File "E:/python_ide/dc_test/test7.py", > > line 57, in <module> > print(str1.index(str2,3)) > ValueError: substring not found

count#

统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。

Copy
str.count(sub, start= 0, end=len(string))
  • sub -- 搜索的子字符串
  • start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
  • end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
  • 该方法返回子字符串在字符串中出现的次数。没有则返回0
Copy
str1 = '0123456' print(str1.count('1')) print(str1.count('1', 0)) print(str1.count('1', 0, len(str1))) print(str1.count('1', 2, 3)) > 1 > 1 > 1 > 0

isalpha、isdigit、isalnum、isspace#

  • isalpha:检测字符串是否只由字母组成。
  • isdigit:检测字符串是否只由数字组成。如果字符串只包含数字则返回 True 否则返回 False。
  • isalnum:检测字符串是否由字母和数字组成。
  • isspace:检测字符串是否只由空格组成。
Copy
str.isalpha() str.isdigit() str.isalnum() str.isspace()
Copy
str1 = '0123456' str2 = 'ABCDE' str3 = 'AB123' str4 = ' ' print(str1.isdigit()) print(str2.isalpha()) print(str3.isalnum()) print(str4.isspace()) > True > True > True > True

isupper、islower#

  • isupper: 检测字符串中所有的字母是否都为大写。如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False
Copy
str.isupper()
Copy
str = "THIS IS STRING EXAMPLE....WOW!!!" print (str.isupper()) str = "THIS is string example....wow!!!" print (str.isupper()) > True > False
  • islower:检测字符串是否由小写字母组成。如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
Copy
str.islower()
Copy
str = "RUNOOB example....wow!!!" print(str.islower()) str = "runoob example....wow!!!" print(str.islower()) > False > True

startswith、endswith#

  • startswith:检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。
Copy
str.startswith(substr, beg=0,end=len(str))
  • str -- 检测的字符串。
  • substr -- 指定的子字符串。
  • strbeg -- 可选参数用于设置字符串检测的起始位置。
  • strend -- 可选参数用于设置字符串检测的结束位置。
Copy
str = "this is string example....wow!!!" print (str.startswith( 'this' )) # 字符串是否以 this 开头 print (str.startswith( 'string', 8 )) # 从第八个字符开始的字符串是否以 string 开头 print (str.startswith( 'this', 2, 4 )) # 从第2个字符开始到第四个字符结束的字符串是否以 this 开头 > True > True > False
  • endswith:判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回 True,否则返回 False。可选参数 "start" 与 "end" 为检索字符串的开始与结束位置。
Copy
str.endswith(suffix[, start[, end]])
  • suffix -- 该参数可以是一个字符串或者是一个元素。
  • start -- 字符串中的开始位置。
  • end -- 字符中结束位置。
Copy
Str='Runoob example....wow!!!' suffix='!!' print (Str.endswith(suffix)) print (Str.endswith(suffix,20)) suffix='run' print (Str.endswith(suffix)) print (Str.endswith(suffix, 0, 19)) > True > True > False > False

upper、lower、title、capitalize、swapcase#

  • lower:将字符串中的大写字母转为小写字母。
  • upper:将字符串中的小写字母转为大写字母。
  • title:将所有单词首字母转为大写,其余字母均转为小写。
  • capitalize:将字符串的第一个字母转为大写,其他字母转为小写。
  • swapcase:将字符串做大小写字母转换(大写->小写,小写->大写)
Copy
str.lower() str.upper() str.title() str.capitalize() str.swapcase()
Copy
>>> 'aBcDe'.upper() 'ABCDE' >>> 'aBcDe'.lower() 'abcde' >>> 'thIs is a exaMple'.title() 'This Is A Example' >>> 'this is A example'.capitalize() 'This is a example' >>> 'aBcDe'.swapcase() 'AbCdE'

strip、lstrip、rstrip#

  • strip(): 方法用于移除字符串头尾指定的字符(默认为空格)或字符序列。只能删除开头或是结尾的字符,不能删除中间部分的字符。
  • lstrip() :方法用于截掉字符串左边的空格或指定字符。
  • rstrip(): 删除 string 字符串末尾的指定字符(默认为空格).
Copy
str.strip([chars]) str.lstrip([chars]) str.rstrip([chars])
Copy
>>> ' abc '.strip() 'abc' >>> ' abc'.lstrip() 'abc' >>> 'abc '.rstrip() 'abc' >>> 'abc'.strip('a') 'bc' >>> 'abc'.lstrip('a') 'bc' >>> 'abc'.rstrip('c') 'ab' >>> 'abc@163.com'.strip('cawm') 'bc@163.co' >>> 'abc@163.com'.lstrip('cawm') 'bc@163.com' >>> 'abc@163.com'.rstrip('cawm') 'abc@163.co'

split、splitlines、partition、rpartition#

  • split:指定分隔符对字符串进行切片,如果参数 num 有指定值,则仅分隔 num 个子字符串。

  • splitlines:按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。

  • partition:根据指定的分隔符将字符串进行分割。如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。

  • rpartition:类似于partition()函数,只不过是从右边开始。

Copy
str.split(str="", num=string.count(str))
  • str -- 分隔符,以它为界分割。默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
  • num -- 分割次数。默认为 -1, 即分隔所有。
Copy
str = "this is string example....wow!!!" print (str.split( )) # 以空格为分隔符 print (str.split('i',1)) # 以 i 为分隔符 print (str.split('w')) # 以 w 为分隔符 ['this', 'is', 'string', 'example....wow!!!'] ['th', 's is string example....wow!!!'] ['this is string example....', 'o', '!!!']
Copy
str.splitlines([keepends])
  • keepends -- 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
Copy
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines() ['ab c', '', 'de fg', 'kl'] >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(True) ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
Copy
str.partition(str)
  • str-- 指定的分隔符。
Copy
str.rpartition(str)
Copy
>>> 'www.example.com'.partition('.') ('www', '.', 'example.com') >>> 'www.example.com'.rpartition('.') ('www.example', '.', 'com')

填充ljust、center、rjust#

  • ljust:返回一个指定的宽度 width 居左的字符串,fillchar 为填充的字符,默认为空格。如果指定的长度小于原字符串的长度则返回原字符串。

  • center:返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。如果指定的长度小于原字符串的长度则返回原字符串。

  • rjust:返回一个指定的宽度 width 居右的字符串,fillchar 为填充的字符,默认为空格。如果指定的长度小于原字符串的长度则返回原字符串。

Copy
str.ljust(width[, fillchar]) str.center(width[, fillchar]) str.rjust(width[, fillchar])
  • width -- 字符串的总宽度。
  • fillchar -- 填充字符。
Copy
>>> '[www.example.com]'.ljust(30, '*') '[www.example.com]*************' >>> '[www.example.com]'.rjust(30, '*') '*************[www.example.com]' >>> '[www.example.com]'.center(30, '*') '******[www.example.com]*******' >>> '[www.example.com]'.center(4, '*') '[www.example.com]'
posted @   是小鱼呀  阅读(85)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示
目录