Python标准数据类型(三)字符串

上一篇博客提到了不可变数据,这篇所写到的字符串也是不可变数据之一

创建

# 空字符串的创建
>>> s = ''
>>> type(s)
<class 'str'>

首字母大写(capitalize)

语法:
S.capitalize()

>>> s = 'abc'
>>> s.capitalize()
'Abc'

全部大写(upper)

语法:
upper(…)

>>> s = 'AbC'
>>> s.upper()
'ABC'

全部小写(lower)

语法:
S.lower()

>>> s
'AbC'
>>> s.lower()
'abc'

大写变小写(casefold)

语法:
S.casefold()

S2 = "ß"  #德语
>>> S2.casefold()
'ss'  # 德语中ß的小写是ss

ps:
lower与casefold的区别
lower与casefold都可以将大写转换为小写,但是两者存在一定的区别:
对Unicode时使用casefold,对ASCII时用lower

居中(center)

语法:
S.center(width[, fillchar])

>>> s = 'LOVE'
>>> s.center(11)
'    LOVE   '
>>> s.center(11,'*')
'****LOVE***'

记数(count)

语法:
S.count(sub[, start[, end]])

>>> s = 'I want something just like this'
>>> s.count(s)
1
>>> s.count('s')
3
# 需要统计的是字符,因此也要用""框起来

以指定的编码格式编码字符串(encode)

语法:S.encode(encoding=‘utf-8’, errors=‘strict’)

encoding – 要使用的编码,如"UTF-8"。
errors – 设置不同错误的处理方案。默认为 ‘strict’,意为编码错误引起一个UnicodeError。 其他可能得值有 ‘ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ 以及通过 codecs.register_error() 注册的任何值。

>>>s = "this is string example....wow!!!"
>>> import base64
>>> base64.b64encode(s.encode('utf-8',errors = 'strict'))
b'dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE='

字符串开头/结尾匹配(startswith/endswith)

语法:
S.startswith(prefix[, start[, end]])
S.endswith(suffix[, start[, end]])
返回的值为True或False

>>> s.startswith('w')
False
>>> s.startswith('W')
True
>>> s.endswith('d')
True

指定转换字符串中的 tab 符号(’\t’)转为空格的字符数(expandtabs)

语法:
S.expandtabs(tabsize=8)

>>> s = 'abc\t223'
>>> s
'abc\t223'
>>> s.expandtabs(tabsize = 4)
'abc 223'
>>> s.expandtabs(tabsize = 8)
'abc     223'

ps:
\t 是补全当前字符串长度到8的整数倍,最少 1 个最多 8 个空格。
补多少要看你 \t 前字符串长度。
比如当前字符串长度 10,那么 \t 后长度是 16,也就是补 6 个空格。
如果当前字符串长度 12,此时 \t 后长度是 16,补 4 个空格。

>>>str1 = "this is\tstring example....wow!!!"
>>>str2 = "athis is\tstring example....wow!!!"
>>>str3 = "athis is        string example....wow!!!" 
 # is 和 string 中间输入 8 个空格
>>>print(str1)
this is string example....wow!!!            # \t 前有 7 个字符,补充 0 个空格
>>>print("a"+str1)
athis is        string example....wow!!!    # \t 前有 8 个字符,补充 8 个空格
>>>print(str2)
athis is        string example....wow!!!    # 同上
>>>print(str3)
athis is        string example....wow!!!    # 8 个空格的效果,做对比

查找(find & rfind)

语法:
S.find(sub[, start[, end]])
S.rfind(sub[, start[, end]])
返回所查找的字符串的索引值
find:返回第一次查找到字符串的索引
rfind:返回最后一次找到字符串的索引
没有匹配返回-1

>>> s = 'abcadfg'
>>> s.find('a')
0
>>> s.rfind('a')
3

格式化(format & format_map)

语法:
S.format(*args, **kwargs)
S.format_map(mapping)

>>> s = 'abc{}dd{}234'
>>> s.format('d','1')
'abcddd1234'
>>>hello = "My name is {name},I am {age} years old.I like {hobby}"
>>>hello.format_map({'name':'Qiuqiu','age':21,'hobby':'Koukou'})
'My name is Qiuqiu,I am 21 years old.I like Koukou'

format_map更像是高阶的format,将字典中的参数对应的键值返回字符串中

索引(index & rindex)

语法:
S.index(sub[, start[, end]])
S.rindex(sub[, start[, end]])

>>> str1 = "this is string example....wow!!!"
>>> str1.index('is')
2
>>> str1.rindex('is')
5

与rfind和find相似的是,index返回第一个索引的值,rindex返回最后一次索引的值
与之不同的是,若没有索引到,会返回ValueError

检测字符串是否由字母和数字组成(isalnum)

语法:
S.isalnum()

>>> s
'abc{}dd{}234'
>>> s.isalnum()
False
>> s1 = 'abc123'
>>> s1.isalnum()
True

返回的是True和False,只要不都由字母和数字组成,就返回False

检测字符串是否由字母组成(S.isalpha)

语法:
S.isalpha()

>>> s1
'abc123'
>>> s1.isalpha()
False
>>> s2 = 'abc'
>>> s2.isalpha()
True

检测字符串是否由十进制字符组成(isdecimal)

语法:
S.isdecimal()

>>> s = 'abc123'
>>> s.isdecimal()
False
>>> s1 = '123'
>>> s1.isdecimal()
True

检测字符串是否只由数字组成(isdigit)

语法:
S.isdigit()

>>> s1 = '123'
>>> s1.isdigit()
True

检测字符串是否只由数字组成(isnumeric)

只针对Unicode对象

>>> s1 = '123'
>>> s1.isnumeric()
True

isdecimal & isdigit & isnumeric对比:

TrueFalseError
isdecimalUnicode数字,全角数字(双字节)罗马数字,汉字数字byte数字(单字节)
isdigitUnicode数字,byte数字(单字节)
全角数字(双字节),罗马数字
汉字数字
isnumericUnicode数字,全角数字(双字节)
罗马数字,汉字数字
byte数字(单字节)

检测字符串是否是合法的标识符(isidentifier)

>>> '_a'.isidentifier()
True
>>> '1_a'.isidentifier()
False

检测字符串是否全是大写/小写(isupper/islower)

#大写
>>> 'ABC'.isupper()
True
>>> 'ABc'.isupper()
False
#小写
>>> 'ABc'.islower()
False
>>> 'abc'.islower()
True

检测字符串所包含的字符是否全部可打印(isprintalbe)

>>> 'abc'.isprintable()
True
>>> 'ab\tc'.isprintable()
False

字符串包含不可打印字符,如转义字符,将返回False

检测字符串是否仅包含空格或制表符(isspace)

>>> 'a b'.isspace()
False
>>> ''.isspace()
False
>>> ' '.isspace()
True

空白和空格是不同的
''是空白,' '是空格

检测字符串每个单词的首字母是否大写(istitle)

>>> '啦啦啦Ab'.istitle()
True
>>> 'ABc'.istitle()
False
>>> 'Ab Cd'.istitle()
True
>>> 'Ab CD'.istitle()
False

字符串必须至少包含一个字母字符,否则返回False。
即使首字母字符前面有非字母字符,如中文、数字、下划线等,也不影响对首字母字符的判断。
但是每组必须第一个字母大写,后续字母小写

将序列中的元素以指定的字符连接生成一个新的字符串(join)

语法:
S.join(iterable)

>>> s1 = '*'
>>> s2 = ('a','b','c')
>>> s1.join(s2)
'a*b*c'

将字符串按指定长度左/右对齐(ljust/rjust)

语法:
S.ljust(width[, fillchar])
S.rjust(width[, fillchar])

>>> a = 'Love'
>>> a.ljust(10)
'Love      '
>>> a.ljust(10,'-')
'Love------'
>>> a.rjust(10,'-')
'------Love'

以指定字符为中心返回一个元组(partition/rpartition)

语法:
S.partition(sep)
S.rpartition(sep)

>> a = 'www.abc.hello.world'
('www', '.', 'abc.hello.world')
>>> a.rpartition('.')
('www.abc.hello', '.', 'world')

partition:返回一个三元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串
rpartition:同上,只不过从最后一个sep来进行分割

返回的是字符串的副本,并删除前导和后缀字符(strip)

语法:
S.strip([chars])

>>> s = 'aabcdaaeaa'
>>> s.strip('a')
'bcdaae'

返回的是字符串的副本,删除前导或后缀(lstrip/rstrip)

语法:
S.rstrip([chars])
S.lstrip([chars])

>>>a="babacb111baccbb"
>>>a.lstrip("abc")
111baccbb
>>>a.rstrip("abc")
babacb111

通过指定分隔符对字符串进行切片(split)

sep默认为空字符,包括空格、换行(\n)、制表符(\t)
如果参数 maxsplit 有指定值,则分隔 maxsplit+1 个子字符串
语法:
S.split(sep=None, maxsplit=-1)

>>> a = 'abb c dd e'
>>> a.split()
['abb', 'c', 'dd', 'e']
>>> a.split(' ',2)
['abb', 'c', 'dd e']

rsplit用法同上,但是是从右向左寻找

按照行(’\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表(splitlines)

语法:
S.splitlines([keepends])

>>> a = 'hhh\nxxx\tnnn qqq'
>>> a.splitlines()
['hhh', 'xxx\tnnn qqq']

返回当前old换成new,可选择的替代限制到最大数量的字符串的副本。(replace)

语法:
S.replace(old, new[, count])

>>> a = 'It is a nice day! It is really nice day'
>>> a.replace('is','was')
'It was a nice day! It was really nice day'
>>> a.replace('is','was',1)
'It was a nice day! It is really nice day'

若出现次数大于count参数的值,则从左到右替换count参数次,剩下的不改变

根据参数table给出的表(包含 256 个字符)转换字符串的字符, 要过滤掉的字符放到 del 参数中(translate)

语法:
S…translate(table[, deletechars])

>>>from string import maketrans   # 引用 maketrans 函数。
>>>intab = "aeiou"
>>>outtab = "12345"
>>>trantab = maketrans(intab, outtab)
>>>a = "this is string example....wow!!!"
>>>a.translate(trantab)
th3s 3s str3ng 2x1mpl2....w4w!!!

用于对字符串的大小写字母进行转换(swapcase)

语法:
S.swapcase()

>>> a = 'abcDeFGh'
>>> a.swapcase()
'ABCdEfgH'

返回"标题化"的字符串(title)

语法:
S.title()

>>> a
'abcDeFGh'
>>> a.title()
'Abcdefgh'
>>> b = 'ABcD eFgge'
>>> b.title()
'Abcd Efgge'

返回指定长度的字符串,原字符串右对齐,前面填充0(zfill)

语法:
S.zfill(width)

>>> a = 'hello'
>>> a.zfill(20)
'000000000000000hello'

参考文献:
参考1
参考2
参考3
参考4
参考5
参考6

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值