python 上机实验 字符串
1. % 格式化字符串
-
%o 八进制整数
x = 1234 print('%o' %x) 2322
-
%e 指数(e为基底)
>>> print('%e' %x) 1.234000e+03
-
%x 十六进制整数
>>> print('%x' %x) 4d2
-
%r 专业显示 %s 非专业显示
>>> y = '\nufalsk' >>> print('%r' %y) '\nufalsk' >>> print('%s' %y) ufalsk
2. format() 格式化字符串
-
formatter
>>> weather = [('星期1','下雨'),('星期2','晴天')] >>> formatter = '今天是{0[0]}, 天气{0[1]}'.format >>> for item in weather: ... print(formatter(item)) ... 今天是星期1, 天气下雨 今天是星期2, 天气晴天
-
指定小数位
>>> print('{0:.2f}'.format(10.0/3)) 3.33
-
对齐
-
> num 右对齐num 前面不够补充空格
>>> print('{0:>94}'.format(10.0/3)) 3.33333333333
-
< num 左对齐num 后面不够补空格
>>> print('{0:<94}'.format(10.0/3)) 3.33333333333
-
^ 中间对齐
>>> print('{0:^94}'.format(10.0/3)) 3.33333333333
-
3. 字符串常用函数
-
find() 找到第一次出现的第一个下标
>>> a = '潇洒哥,黑大帅,蛋蛋' >>> a.find('蛋蛋') 20 >>> a.find('潇洒哥') 0 >>> a.find('a') -1 # 找不到返回-1
-
rfind() 从右边找到第一个出现的第一个元素的下标
潇洒哥,黑大帅,蛋蛋潇洒哥, 黑大帅 >>> a.rfind('潇洒哥') 26
-
count() 统计字符串出现次数
>>> a.count('egg') 1
-
split() 按照指定的字符,分割字符串,并且返回相应的列表
>>> a 'handsomeBrother,black,egg,handsomeBrother' >>> a.split(',') ['handsomeBrother', 'black', 'egg', 'handsomeBrother'] >>> a.split('bla') ['handsomeBrother,', 'ck,egg,handsomeBrother']
-
partition() 按照指定字符,将字符串分割为3段
>>> a.partition(',') ('handsomeBrother', ',', 'black,egg,handsomeBrother')
-
rpartition() 按照指定字符,从右边选择删除
>>> a.rpartition(',') ('handsomeBrother,black,egg', ',', 'handsomeBrother') >>> a.partition('0') ('handsomeBrother,black,egg,handsomeBrother', '', '') # 如果指定对象不存在,则会在末尾瞎J儿乱删除
-
join() 以指定字符,连接列表中的字符串
>>> b ['handsomeBrother', 'black', 'egg', 'handsomeBrother'] >>> ','.join(b) 'handsomeBrother,black,egg,handsomeBrother' >>> b.append(1) >>> b ['handsomeBrother', 'black', 'egg', 'handsomeBrother', 1] >>> ','.join(b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 4: expected string, int found # 不支持其他类型
-
lower() 全部小写
>>> c = "ARE YOU PIG?" >>> c.lower() 'are you pig?'
-
upper() 全部大小
>>> d 'are you pig?' >>> d.upper() 'ARE YOU PIG?'
-
capitalize() 第一个字母大写,其余全部小写
>>> c 'ARE YOU PIG?' >>> c.capitalize() 'Are you pig?' >>> d # 但是第一个不是字母,那就不会寻找第一个单词将它变成大小,而是全部小写 ' 009ARE YOU PIG?' >>> d.capitalize() ' 009are you pig?'
-
title() titile不管,连续单词第一个全大写,其余全小写
>>> d.title() ' 009Are You Pig?'
-
replace() 替代指定字符串为另一个, 每次替换一个
>>> words ['fuck', 'sun', 'beach'] >>> for word in words: ... e = e.replace(word, '***') ... >>> e '*** you *** of ***'
-
strip() 从两边删除指定对象
>>> a = 'handsomeBrother,black,egg,handsomeBrother' >>> a.rfind('handsomeBrother') 26 >>> a[26] 'h' >>> a.strip('handsomeBrother') ',black,egg,'