Python去除字符串两端空格的方法

作者:junjie 时间:2023-06-14 23:15:40 

目的

获得一个首尾不含多余空格的字符串

方法

可以使用字符串的以下方法处理:

string.lstrip(s[, chars])
Return a copy of the string with leading characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the beginning of the string this method is called on.

string.rstrip(s[, chars])
Return a copy of the string with trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on.

string.strip(s[, chars])
Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

 

具体的效果如下:


In [10]: x='     Hi,Jack!        '

In [11]: print '|',x.lstrip(),'|',x.rstrip(),'|',x.strip(),'|'
| Hi,Jack!         |      Hi,Jack! | Hi,Jack! |

其中提供的参数chars用来删除特定的符号,注意空格并没有被移除,例如:


In [12]: x='yxyxyxxxyy Hello xyxyxyy'

In [13]: print x.strip('xy')
 Hello

标签:Python,去除,字符串,两端,空格
0
投稿

猜你喜欢

  • Python利用pywin32实现自动操作电脑

    2024-01-03 03:35:59
  • 全面解析python当前路径和导包路径问题

    2022-09-08 16:00:21
  • Python 学习教程之networkx

    2023-10-11 01:49:07
  • Python图像运算之图像阈值化处理详解

    2023-03-20 22:36:24
  • 用sqlalchemy构建Django连接池的实例

    2021-09-22 20:20:30
  • Python随机生成数模块random使用实例

    2022-08-04 21:04:48
  • Python实现抓取网页并且解析的实例

    2022-01-12 13:24:53
  • python单向循环链表实例详解

    2023-05-25 01:29:40
  • 远程登陆SQL Server 2014数据库的方法

    2024-01-28 03:39:01
  • 自动定时备份sqlserver数据库的方法

    2024-01-13 20:45:14
  • python基础知识小结之集合

    2021-07-14 23:34:54
  • pytorch绘制并显示loss曲线和acc曲线,LeNet5识别图像准确率

    2023-01-06 11:04:09
  • 探讨SQL利用INFORMATION_SCHEMA系统视图如何获取表的主外键信息

    2024-01-23 04:16:36
  • 初识python的numpy模块

    2021-10-06 10:04:57
  • .NET多种数据库大数据批量插入、更新(支持SqlServer、MySql、PgSql和Oracle)

    2024-01-19 07:39:40
  • uniapp中微信小程序与H5相互跳转以及传参详解(webview)

    2024-04-10 16:20:37
  • XmlUtils JS操作XML工具类

    2024-02-24 14:10:45
  • 如何利用pyinstaller打包Python程序为exe可执行文件

    2023-11-08 08:01:39
  • PHP投票系统防刷票判断流程分析

    2023-09-27 13:34:03
  • 将自己的数据集制作成TFRecord格式教程

    2022-02-01 14:49:37
  • asp之家 网络编程 m.aspxhome.com