字符串常用处理方法

lstrip()

  lstrip()去除字符串左边的空格,也可使用lstrip('#')去除字符串左边的"#"等

s=' A B C D '
# 去除左边空格
print(s.lstrip())

rstrip()

  rstrip()去除字符串右边的空格,也可使用rstrip('#')去除字符串左边的"#"等

s=' A B C D '
# 去除右边空格
print(s.rstrip())

strip()

  去除左右两边的空格,也可使用strip('#')去除字符串左右两边的"#"等

s=' A B C D '
# 去除左右两边空格
print(s.strip())

re.sub

  使用正则表达式去除字符串中所有的空格

import re
s=' A B C D '
print(re.sub('\s','',s))

split()

  分割字符串,可以使用指定字符分割字符串(s.split('a'))

s=' A B C D '
# 以空格分隔字符串
print(s.split())

  多种分割,指定的分割字符串不唯一时可以使用正则表达式分割

# 多种分割
time=' 2018/07/02 15:35:20'
print(re.split(r'[/\s:]+',time.strip()))

\b

  使用\b查找字符串,\b匹配一个单词边界,也就是指单词和空格间的位置,例如'lo\b'可以匹配‘hello’中的‘lo’,但不能匹配'loli'中的'lo'

#使用\b查找指定字符
context='''
When I was One
I had just begun
When I was Two
I was nearly new
'''
print(re.findall(r'\bwas\b',context.lower()))

\B

  匹配非单词边界,例如'lo\B'可以匹配'loli'中的'lo',但不能匹配‘hello’中的‘lo’

#使用\B查找指定字符
context='''
When I was One
I had just begun
When I was Two
I was nearly new
'''
print(re.findall(r'near\B',context.lower()))

猜你喜欢

转载自www.cnblogs.com/iamluoli/p/9254159.html
今日推荐