美文网首页
Python-字符串去掉空格

Python-字符串去掉空格

作者: 冲锋丘丘人 | 来源:发表于2019-06-14 15:27 被阅读0次

前言

使用Django开发web项目,搜索框输入的值包含空格,导致后台查询不到数据,这个时候就需要对字符串做去空格处理。

方法

  • strip():把头和尾的空格去掉

  • lstrip():把左边的空格去掉

  • rstrip():把右边的空格去掉

  • replace('c1','c2'):把字符串里的c1替换成c2。故可以用replace(' ','')来去掉字符串里的所有空格

  • split():通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串

实例

list = "  dsdf dfasf dfas dfsf  "
print("初始:"+list)
listone = list.strip()
listtwo = list.rstrip()
listthree = list.lstrip()
print("去除两边空格:"+listone)
print("去除左边空格:"+listtwo)
print("去除右边空格:"+listthree)

###输出
初始:  dsdf dfasf dfas dfsf  
去除两边空格:dsdf dfasf dfas dfsf
去除左边空格:  dsdf dfasf dfas dfsf
去除右边空格:dsdf dfasf dfas dfsf  

相关文章

网友评论

      本文标题:Python-字符串去掉空格

      本文链接:https://www.haomeiwen.com/subject/cskpfctx.html