1、字符串分割:str.split() 或者使用正则 re.split()
2、字符串开头或结尾匹配:str.startswith()(开头)、str.endswith()(结尾)
3、字符串匹配和搜索:str.find() 或者使用正则 re.findall()
4、字符串搜索和替换:str.replace() 或者使用正则 re.sub() ;想知道有多少替换发生了,可以使用 re.subn() 来代替
5、删除字符串中不需要的字符:str.strip() 方法能用于删除开始或结尾的字符。 str.lstrip() 和 str.rstrip() 分别从左和从右执行删除操作。 默认情况下,这些方法会去除空白字符,但是你也可以指定其他字符。同时也可以使用str.replace()或re.sub()
例:
t = ‘-----hello=====’
t.lstrip(’-’) # ‘hello=====’
t.strip(’-=’) # ‘hello’
5、文本转为标准格式:str.upper()(大写)、str.lower()(小写)
6、字符串对齐:str.ljust()(左对齐) , str.rjust()(右对齐) 和 str.center()(居中)。也可以使用函数 format() ,就是使用 <,> 或者 ^ 字符后面紧跟一个指定的宽度。
例如:
format(‘hello world’, ‘>20’) #’ Hello World’
format(‘hello world’, ‘<20’) #‘Hello World ’
format(‘hello world’, ‘^20’) #’ Hello World ’
format(‘hello world’, ‘*^20s’) #‘Hello World*’
7、合并拼接字符串:str.join()
8、以指定列宽格式化字符串:使用 textwrap 模块来格式化字符串的输出。
例:
s = “Look into my eyes, look into my eyes, the eyes, the eyes,
the eyes, not around the eyes, don’t look around the eyes,
look into my eyes, you’re under.”
import textwrap
print(textwrap.fill(s, 40))
输出如下:
Look into my eyes, look into my eyes,
the eyes, the eyes, the eyes, not around
the eyes, don't look around the eyes,
look into my eyes, you're under.
print(textwrap.fill(s, 40, initial_indent=' '))
输出如下:
Look into my eyes, look into my
eyes, the eyes, the eyes, the eyes, not
around the eyes, don't look around the
eyes, look into my eyes, you're under.
print(textwrap.fill(s, 40, subsequent_indent=' '))
输出如下:
Look into my eyes, look into my eyes,
the eyes, the eyes, the eyes, not
around the eyes, don't look around
the eyes, look into my eyes, you're
under.
9、在字符串中处理html和xml。使用 html.escape() 函数,替换文本字符串中的 ‘<’ 或者 ‘>’
例:
s = ‘Elements are written as “text”.’
import html
print(html.escape(s)) #Elements are written as “<tag>text</tag>”.
print(html.escape(s, quote=False)) #Elements are written as “<tag>text</tag>”.
s = ‘Spicy "Jalapeño".’
from html.parser import HTMLParser
p = HTMLParser()
p.unescape(s) # ‘Spicy “Jalapeño”.’
t = ‘The prompt is >>>’
from xml.sax.saxutils import unescape
unescape(t) # ‘The prompt is >>>’