有勇气的牛排博客

python 删除字符串中空格

有勇气的牛排 204 Python 2023-05-18 20:31:08

1. strip() 删除字符串 开头 和 结尾 的空格
str = ' a b c ' print(str.strip())
2. lstrip() 删除字符串 开头 所有空格
str = ' a b c ' res = str.lstrip() print(res)
3. 删除字符串 结尾 的空格
str = ' a b c ' print(str.rstrip())
4. 删除 全部 空格

①replace()

str = " a b c " print(str.replace(" ", ""))

②’’.join(str.split())

str = " a b c " res = ''.join(str.split()) print(res)

③正则

import re str = ' I love you ! ! !' res = re.sub('\s+', '', str).strip() print(res)

留言

专栏
文章
加入群聊