Python——字符串处理

字符串处理

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
  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值