Python字符串操作相关问题

1、字符串不区分大小写替换

str.replace(old, new[, max])的替换是区分大小写的。不区分大小写替换需要正则表达式re.sub()带上re.IGNORECASE选项。

1
2
3
4
>>> import re
>>> reg = re.compile(re.escape('hello'), re.IGNORECASE)
>>> reg.sub('My', 'Hello World, HELLO PYTHON')
'My World, My PYTHON'

2、字符串大小写转换

str.lower() 字符串全小写。
str.upper() 字符串全大写。
str.capitalize() 字符串首字母大写。
str.title() 字符串每个单词首字母都大写。

1
2
3
4
5
6
7
8
9
>>> str = 'my world, MY PYTHON'
>>> str.lower()
'my world, my python'
>>> str.upper()
'MY WORLD, MY PYTHON'
>>> str.capitalize()
'My world, my python'
>>> str.title()
'My World, My Python'

3、字符串是否以某一个子串开头或结尾

str.startswith() 检测字符串是否以某一子串开头。
str.endswith() 检测字符串是否以某一子串结尾。
如需检测多个值,则用元组作为参数。

1
2
3
4
5
6
7
8
>>> import os
>>> filenames = os.listdir('.')
>>> filenames
[ 'Makefile', 'foo.c', 'bar.py', 'spam.c', 'spam.h' ]
>>> [name for name in filenames if name.endswith(('.c', '.h')) ]
['foo.c', 'spam.c', 'spam.h'
>>> any(name.endswith('.py') for name in filenames)
True

4、匹配字符串连续的重复字符

(\w)匹配字母数字下划线即[a-zA-Z0-9_]
((\w)\2)匹配重复的字符,其中\2匹配分组number是2的分组,因为最外层有圆括号,所以number是2的分组就是前面\w匹配的字符
((\w)\2+)匹配重复出现2次或以上的字符

1
2
3
4
5
6
7
>>> import re
>>> str = 'aaabccc11fdsa'
>>> re.findall(r'((\w)\2+)', str)
[('aaa', 'a'), ('ccc', 'c'), ('11', '1')]
>>> [match[0] for match in re.findall(r'((\w)\2+)', str)]
['aaa', 'ccc', '11']
>>>
大师兄 wechat
欢迎关注我的微信公众号:Python大师兄