python字符串操作

2019-11-23  本文已影响0人  站在巨人的肩膀上努力着
a = u'嘉義縣大林鎮112111gggg!!!aaaBBB'
if u'aaa' in a:
    print 'ok'
else:
    print 'no'
if u'AAA' in a:
    print 'ok'
else:
    print 'no'

输出结果是
ok
no
注意:此处区分大小写

import re

#不带括号
string="abcdefg  acbdgef  abcdgfe  cadbgfe"
regex=re.compile("((\w+)\s+\w+)")
print regex.findall(string)

regex1=re.compile("(\w+)\s+\w+")
print regex1.findall(string)

regex2=re.compile("\w+\s+\w+")
print regex2.findall(string)

上面输出结果是:
[('abcdefg acbdgef', 'abcdefg'), ('abcdgfe cadbgfe', 'abcdgfe')]
['abcdefg', 'abcdgfe']
['abcdefg acbdgef', 'abcdgfe cadbgfe']
注意:带括号与不带括号的区别

#\d 匹配一个数字字符。等价于 [0-9]
#\D 匹配一个非数字字符。等价于 [^0-9]

#过滤字符串中的英文与符号,保留汉字
import re
st = "hello,world!!%[545]你好234世界。。。"
ste = re.sub("[A-Za-z0-9\!\%\[\]\,\。]", "", st)
print ste

#从字符串中提取数字
totalCount = '100abc'
totalCount = re.sub("\D", "", totalCount)
print totalCount

#从字符串中提取字母字符串
import re
st = "hello,world!!%[545]你好234世界。。。"
result = ''.join(re.findall(r'[A-Za-z]', st))
print result

输出结果是:
你好世界
100
helloworld

print 'daydayupup'.find("day")

输出结果是0

上一篇下一篇

猜你喜欢

热点阅读