正则表达式的用法:
字符串忽略大小写的搜索替换,最长匹配
findall()& sub()
最短匹配模式
compile()
?表示0个或者1个
删除字符串中不需要的字符
strip()和rstrip()分别去掉开头护额结尾空白
字符串对齐ljust()和rjust()设置长度
合并拼接字符串
{}{}。format(,)
‘’.join(【】)
'hello{name}'.forma(name=‘snow’)
正则表达式的用法:
字符串忽略大小写的搜索替换,最长匹配
findall()& sub()
最短匹配模式
compile()
?表示0个或者1个
删除字符串中不需要的字符
strip()和rstrip()分别去掉开头护额结尾空白
字符串对齐ljust()和rjust()设置长度
合并拼接字符串
{}{}。format(,)
‘’.join(【】)
'hello{name}'.forma(name=‘snow’)
Python讨论-字符串13个场景(二)
1.字符串忽略大小写的搜索替换
2.最短匹配模式
3.多行匹配模式
使用正则表达式去匹配一大块的文本,而文本是跨越多行去匹配。
4.删除字符串中不需要的字符
去掉文本字符串开头,结尾或者中间不想要的字符,比如空白。
>>> s='hello world\n'
>>> s.strip()
'hello world' #去掉开头,中间结尾的空 格,换行符等。
>>> s.lstrip()
'hello world\n' #去掉前边的空格,换行符 等。
>>> s.rstrip()
'hello world' #去掉结尾的空格,换行符等
>>> s='hello world\n'
>>> import re
>>> re.sub(r'\s+','',s)
'helloworld'
>>> re.sub(r'\s+',' ',s)#将多个空格换成 一个空格。
'hello world '
5.字符串对齐
6.合并拼接字符串
创建一个内嵌变量的字符串,变量被它的值所表示的字符串替换掉。
>>> a='hello'
>>> b='world'
>>> a+''+b
'helloworld'
>>> a+' '+b
'hello world'
>>> '{}{}'.format(a,b)
'helloworld'
>>> '{} {}'.format(a,b)
'hello world'
>>> ' '.join([a,b])
'hello world'
>>> a=print(a,b)
hello world
7.字符串中插入变量
几个小的字符串合并为一个大的字符串。
8.以指定列宽格式化字符串
import re
re.findall('replace','Replace,replace,REPLACE',flags=re.IGNORECASE)如果没有最后一个是要看大小写的
re.sub(a,b,c,flags=re.IGNORECASE)这是将c里面所有的a换成b
r=re.compile(r'****')生成的是一种正则表达式r'\"(.*?)\"'这是最短匹配加()可以只获得括号内的东西可以不用'/\*(.*?)\*/’两边的
匹配多行要两边的/
r.findall(text) /\*((?:.|\n)*?)\*/
或者用'/\*(.*?)\*/’,re.DOTALL就可以多行匹配,第二种更好
print('a','b')
结果为元组
import textwrap
textwrap.fill(zifuchuan,40)每40个换一行
不会分开单词
合并拼接字符串
>>>a='hello'
>>>b='world'
>>>a+''+b
'hello world'
>>>'{}{}'.format(a,b)
'hello world'
>>>''.join([a,b])
'hello world'
>>>a=print(a,b)
hello world
字符串中插入变量
几个小的字符串合并为一个大的字符串
>>>'my name is {name}.'.format(name='abby')
'my name is abby'
>>>format(text,'>20')
' hello world'
>>>'{:>10s}{:>10s}'.format('hello','world')
' hello world'
>>>'%-20s' % text
'hello world '
以指定列宽格式化字符串
>>>longtext="hello world! hello world! hello world! hello world! \
...hello world! hello world! hello world! hello world! hello world! \
...hello world! hello world! hello world! hello world! hello world! "
>>>import textwrap
>>>textwrap.fill(longtext,40)
'hello world! hello world! hello world!\nhello world! hello world! hello world! \nhello world! hello world! hello world! \nhello world! hello world! hello world! \nhello world! hello world! '
>>>print(textwrap.fill(longtext,40))指定宽度40
hello world! hello world! hello world!
hello world! hello world! hello world!
hello world! hello world! hello world!
hello world! hello world! hello world!
hello world! hello world!
6.字符串忽略大小写的搜索替换(re.findall,re.sub)
7.最短匹配(两个双引号之间的内容)
8.多行匹配模式(\* *\之间的内容)
9.删除字符串中不需要的字符
10.字符串对齐
11.合并拼接字符串(使用+,join,format)
12.字符串中插入变量
13.以指定列宽格式化字符串
搜索替换:
re.findall('s','string,s,t',flags = re.IGNORECASE)
第一个字符串替换第二个字符串;flags 表示忽略大小写