Python之旅——令人头疼的字符串

字符串一直是我的软肋
从Pascal到C++,只要是字符串我就头痛欲裂
希望这个噩梦不要延续到Python(TwT)


前情提要

我们在之前的文章中,介绍了字符串的定义方法

我一直有一个很“初学者”的疑问:
为什么在字符串定义中,单引号和双引号没有肉眼可见的区别呢
实际上,Python确实在一定意义上消除了ta们之间的区别

我觉得这个大大讲的非常详细,可以移步去简单了解一下,再回来继续哦
(够了。。。C_T你就是想偷懒,不要掩饰了)

其实,字符串和元组非常相似
这就提示我们,字符串不支持单个字符的修改操作(和元组相同),但是可以对字符串进行分片

我在这里重申一遍分片的定义:
[ a , b ] a b 1 [a,b]表示截取下标从a到b-1的片段

str1 = 'hello world'

>>> str1[0]
'h'
>>> str1[0] = 'H'
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    str1[0] = 'H'
TypeError: 'str' object does not support item assignment
>>> str1[0:5]
'hello'

如果要修改字符串,我们只能依靠分片:

str1 = 'H' + str1[1:] + '!'
>>> str1
'Hello world!'

其余的操作和列表大同小异(这里就不在一一介绍了),包括:

  • 比较操作符
  • 逻辑操作符
  • 连接操作符
  • 重复操作符
  • 成员关系操作符

常用字符串内置函数

我们最关心的还是字符串类型的内置函数

函数 作用
c a p i t a l i z e ( ) capitalize() 首字母大写,其余小写
u p p e r ( ) upper() 全部大写
l o w e r ( ) lower() 全部小写
c a s e f o l d ( ) casefold() 全部小写(效果与 l o w e r ( ) lower() 相同)
c e n t e r ( w i d t h ) center(width) 返回一个居中字符串,并用空格填充长度至 w i d t h width
c o u n t ( s u b [ , s t a r t [ , e n d ] ] ) count(sub[,start[,end]]) 返回 s u b sub 在字符串里出现的次数, s t a r t start e n d end 参数表示范围,可选
e n d s w i t h ( s u b [ , s t a r t [ , e n d ] ] ) endswith(sub[,start[,end]]) 检查字符串是否以 s u b sub 子串结尾,如果是返回 T r u e True ,否则返回 F a l s e False s t a r t start e n d end 参数表示范围,可选
e x p a n d t a b s ( [ t a b s i z e = 8 ] ) expandtabs([tabsize=8]) 把字符串中的 t a b tab 符号(\t)转换成空格,如果不指定参数,默认空格数是 t a b s i z e = 8 tabsize=8
f i n d ( s u b [ , s t a r t [ , e n d ] ] ) find(sub[,start[,end]]) 检查 s u b sub 是否包含在字符串中,如果有返回索引值,否则返回-1, s t a r t start e n d end 参数表示范围,可选
i n d e x ( s u b [ , s t a r t [ , e n d ] ] ) index(sub[,start[,end]]) 检查 s u b sub 是否包含在字符串中,如果不在则抛出一个异常
i s a l n u m ( ) isalnum() 如果字符串至少有一个字符且所有字符都是字母或数字,返回 T r u e True ,否则返回 F a l s e False
i s a l p h a ( ) isalpha() 如果字符串至少有一个字符且所有字符都是字母,返回 T r u e True ,否则返回 F a l s e False
i s d e c i m a l ( ) isdecimal() 如果字符串只包含十进制数字则返回 T r u e True ,否则返回 F a l s e False
i s d i g i t ( ) isdigit() 如果字符串只包含数字则返回 T r u e True ,否则返回 F a l s e False
i s l o w e r ( ) islower() 如果字符串中至少包含一个区分大小写的字符,且所有字符都是小写,则返回 T r u e True ,否则返回 F a l s e False
i s u p p e r ( ) isupper() 如果字符串中至少包含一个区分大小写的字符,且所有字符都是大写,则返回 T r u e True ,否则返回 F a l s e False
i s n u m e r i c ( ) isnumeric() 如果字符串只包含数字字符则返回 T r u e True ,否则返回 F a l s e False
i s s p a c e ( ) isspace() 如果字符串只包含空格则返回 T r u e True ,否则返回 F a l s e False
i s t i t l e ( ) istitle() 如果字符串是标题化的(所有单词首字母大写,其余字母小写)则返回 T r u e True ,否则返回 F a l s e False
j o i n ( s u b ) join(sub) 以字符串为分隔符,插入到sub中所有的字符之间
l j u s t ( w i d t h ) ljust(width) 返回一个左对齐的字符串,并用空格填充长度至 w i d t h width
l s t r i p ( ) lstrip() 去掉字符串左端的所有空格
p a r t i t i o n ( s u b ) partition(sub) 找到子串 s u b sub ,把字符串分为一个3元组 ( p r e _ s u b , s u n , f o l _ s u b ) (pre\_sub,sun,fol\_sub) ,如果原字符串中不包含 s u b sub 则返回(原字符串,’ ‘,’ ')
r e p l a c e ( o l d , n e w [ , c o u n t ] ) replace(old,new[,count]) 把字符串中的 o l d old 子串替换成 n e w new 子串,如果 c o u n t count 指定,则替换次数比超过 c o u n t count
r f i n d ( s u b [ , s t a r t [ , e n d ] ] ) rfind(sub[,start[,end]]) 类似 f i n d ( ) find() ,从右查找
r i n d e x ( ) rindex() 类似 i n d e x ( ) index() ,从右查找
r j u s t ( w i d t h ) rjust(width) 返回一个右对齐的字符串,并用空格填充长度至 w i d t h width
r p a r t i t i o n ( s u b ) rpartition(sub) 类似 p a r t i t i o n ( ) partition() ,从右查找
r s t r i p ( ) rstrip() 删除字符串末尾空格
s t a r t s w i t h ( s u b [ , s t a r t [ , e n d ] ] ) startswith(sub[,start[,end]]) 检查字符串是否以 s u b sub 子串开头,如果是返回 T r u e True ,否则返回 F a l s e False s t a r t start e n d end 参数表示范围,可选
s t r i p ( [ c h a r ] ) strip([char]) 删除两端空格,可以指定删除字符
s w a p c a s e ( ) swapcase() 翻转字符串中的大小写
t i t l e ( ) title() 返回标题化字符串
s p l i t ( s e p = N o n e , m a x s p l i t = 1 ) split(sep=None,maxsplit=-1) 无参数时表示按空格分割字符串, m a x s p l i t maxsplit 表示分割子串的数量,返回一个列表
s p l i t l i n e s ( [ k e e p e n d s ] ) splitlines([keepends]) 按照’\n’分割, k e e p e n d s keepends 表示返回前 k e e p e n d s keepends 行,返回一个列表
t r a n s l a t e ( t a b l e ) translate(table) 根据 t a b l e table 转换字符( s t r . m a k e t r a n s ( a , b ) str.maketrans('a','b')
z f i l l ( w i d t h ) zfill(width) 返回长度为 w i d t h width 的字符串,原字符串右对齐,前边用0填充
>>> str1 = 'may the forth be with you'

>>> str1.capitalize()
'May the forth be with you'

>>> str1.upper()
'MAY THE FORTH BE WITH YOU'

>>> str2 = 'I am YOU faTHer'

>>> str2.lower()
'i am you father'

>>> str3 = 'HELLO'

>>> str3.center(15)
'     HELLO     '

>>> str3.count('L')
2

>>> str1 = 'may the forth be with you'
>>> str1.endswith('you')
True
>>> str1.endswith('You')
False
>>> str1.startswith('may')
True
>>> str1.startswith('May')
False

>>> str3 = 'I\tlove\tyou'

>>> str3.expandtabs()
'I       love    you'

# expandtabs到底是怎么回事我也不太清楚...
str3 = '***\t******\t'
>>> str3.expandtabs()
'***     ******  '
>>> str3 = '***\t*********\t'
>>> str3.expandtabs()
'***     *********       '

>>> str4 = 'The boy is unber the apple tree, thingking something.'

>>> str4.find('th')
17
>>> str4.find('this')
-1
>>> str4.rfind('th')
47

>>> str4 = '搞咩啊'
>>> str4.islower()
False
>>> str4 = '?what?'
>>> str4.islower()
True

>>> str5 = 'CocoT'
>>> str5.istitle()
False
>>> str5.title()
'Cocot'

>>> str5 = 'SPACE'
>>> str5.join('love')
'lSPACEoSPACEvSPACEe'

>>> str6 = '   How do u do?   '

>>> str6.lstrip()
'How do u do?   '
>>> str6.rstrip()
'   How do u do?'
>>> str6.strip()
'How do u do?'

>>> str6 = 'hello world'
>>> str6.partition('o ')
('hell', 'o ', 'world')

>>> str4 = 'The boy is unber the apple tree, thingking something.'
>>> str4.replace('the','THAT')
'The boy is unber THAT apple tree, thingking something.'

>>> str6 = 'How do you do?'
>>> str6.split()
['How', 'do', 'you', 'do?']
>>> str6.split('do')
['How ', ' you ', '?']

>>> str7 = 'Coco_T_'
>>> str7.swapcase()
'cOCO_t_'

# translate的用法需要注意一下
>>> str8 = 'ababababa'
>>> str8.translate(str.maketrans('b','B'))
'aBaBaBaBa'

还有疑问就戳这里


格式化

什么时格式化?就是将文本转换成特定的格式输出
在这一部分,我们先介绍Python字符串中的一个特殊的内置函数 f o r m a t format

疲惫的C_T决定用栗子解释:

在原字符串中用花括号表示需要替换的字符串,在format中重新设置

>>> "{0} love {1}".format('I','you')
'I love you'

也可以用关键字标记需要替换的字符串
需要注意的是,format中的字符串设置需要用关键字标明

>>> "{a} love {b}".format(a='I',b='Python')
'I love Python'

当然我们也可以将数字和关键字混用
不过按照规定,关键字一定要出现在数字的后面,否则会出现编译错误

>>> "{0} love {a}".format('I',a='you')
'I love you'

下面是一种很迷人的小用法,可以自己参悟一下

>>> "{0:.2f}{1}".format(3.1415926,'@')
'3.14@'

如果想要打印花括号,需要在花括号外面再套花括号:{{}}

>>> "{{}}".format()
'{}'

下面就是一些又臭又长的总结表格(我会尽量给出一些走心的栗子)

字符串格式化符号
符号 说明
%c 格式化字符及其 ASCII 码
%s 格式化字符串
%d 格式化整数
%o 格式化无符号八进制数
%x 格式化无符号十六进制数
%X 格式化无符号十六进制数(大写)
%f 格式化浮点数字,可指定小数点后的精度
%e 用科学计数法格式化浮点数
%E 作用同 %e,用科学计数法格式化浮点数
%g 根据值的大小决定使用 %f 或 %e
%G 作用同 %g,根据值的大小决定使用 %f 或者 %E
>>> '%c' % 97
'a'

>>> '%c %c %c' % (97,98,99)
'a b c'

>>> '%s' % 'I love you'
'I love you'

>>> '%d + %d = %d' % (4,5,4+5)
'4 + 5 = 9'

>>> '%o' % 10
'12'

>>> '%x' % 76
'4c'

>>> '%X' % 160
'A0'

>>> '%f' % 2.141
'2.141000'

>>> '%e' % 2.141
'2.141000e+00'

>>> '%g' % 34.2657
'34.2657'
格式化操作符辅佐命令
符号 说明
m.n m 是显示的最小总宽度,n 是小数点后的位数
- 用于左对齐
+ 在正数前面显示加号(+)
# 在八进制数前面显示 ‘0o’,在十六进制数前面显示 ‘0x’ 或 ‘0X’
0 显示的数字前面填充 ‘0’ 取代空格
# 这些操作符需要与字符串格式化符号连用

>>> '%.2f' % 23.647
'23.65'

>>> '%.4e' % 3.1415926
'3.1416e+00'

>>> '%10c' % '*'
'         *'

>>> '%-5c' % '@'
'@    '

>>> '%+d' % 9
'+9'

>>> '%+d' % -9
# 针对负数是不会有影响的
'-9'

>>> '%#o' % 10
'0o12'

>>> '%#x' % 76
'0x4c'

>>> '%05d' % 3
'00003'

>>> '%-05d' % 3
# -表示左对齐
'3    '
Python 的转义字符及其含义
符号 说明
单引号
" 双引号
\a 发出系统响铃声
\b 退格符
\n 换行符
\t 横向制表符(TAB)
\v 纵向制表符
\r 回车符
\f 换页符
\o 八进制数代表的字符
\x 十六进制数代表的字符
\0 表示一个空字符
\\ 反斜杠
发布了951 篇原创文章 · 获赞 205 · 访问量 33万+

猜你喜欢

转载自blog.csdn.net/wu_tongtong/article/details/104327769