字符串处理
1.去掉头尾空格 .strip()
- strip() 用来去除头尾字符、空白符(包括\n、\r、\t、’ ',即:换行、回车、制表符、空格)
st = ' hello python '
print(st)
print(st.strip())
输出结果:
hello python
hello python
2.去掉头部空格 .lstrip()
- lstrip() 用来去除开头字符、空白符(包括\n、\r、\t、’ ',即:换行、回车、制表符、空格)
st = ' hello python '
print(st)
print(st.lstrip())
输出结果:
hello python
hello python
3.去掉尾部空格 .rstrip()
- rstrip() 删除 string 字符串末尾的指定字符,默认为空白符,包括空格、换行符、回车符、制表符。
st = ' hello python '
print(st)
print(st.rstrip())
输出结果:
hello python
hello python
4.字符串替换 .replace()
- replace() ⽅法把字符串中的(旧字符串)替换成(新字符串),如果指定第三个参数,则替换不超过MAX次
st = ' hello python '
print(st)
print(st.replace('python', 'word'))
输出结果:
hello python
hello word
5.字符串切片 .split()
-
通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串
-
(包括多个空格,制表符\t,换行符\n等)分割,并返回所有分割得到的字符串
st = ' hello python '
print(st)
print(st.split('python'))
st = ' hello \n python '
print(st)
print(st.split())
输出结果:
hello python
[' hello ', ' ']
['hello', 'python']
6.连接新的字符串 ’ '.join()
- join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串
st = ' hello python '
print(st)
tt = st.split()
t2 = ''.join(tt)
t3 = ','.join(tt)
print(t2)
print(t3)
输出结果:
hello python
hellopython
hello,python
7.换成小写字母 .lower()
st = 'HELLO PYTHON'
print(st.lower())
输出结果:
hello python
8.换成大写字母 .upper()
st = 'hello python'
print(st.upper())
输出结果:
HELLO PYTHON
9.所有单词首字母大写 .title()
st = 'hello python'
print(st.title())
输出结果:
Hello Python
9.大小写字母互换 .swapcase()
st = 'Hello Python'
print(st.swapcase())
输出结果:
hELLO pYTHON
10.首字母大写,其余都小写 .capitalize()
st = 'hello python'
print(st.capitalize())
输出结果:
Hello python
11.换行符,将光标移动到下一行开头 \n
st = 'hello\npython'
print(st)
输出结果:
hello
python
12.换行符,将光标移动到本行开头,(删除前面的内容) \r
st = 'hello\rpython'
print(st)
输出结果:
python
13.制表符,相当于4个空格 \t
st = 'hello\tpython'
print(st)
输出结果:
hello python
14.退格符,将光标移动到前一位 \b
st = 'hello\bpython'
print(st)
输出结果:
hellpython