【Python3学习】常见字符串去除字符串空格的方法

news/2024/7/6 12:02:45

1、replace()方法,可以去除全部空格

语法

str.replace(old, new[, max])
  • old – 将被替换的子字符串。
  • new – 新字符串,用于替换old子字符串。
  • max – 可选字符串, 替换不超过 max 次

实例

str = "this is string example....wow!!! this is really string";

print(str.replace(" ", ""))

#输出 thisisstringexample....wow!!!thisisreallystring

2、strip()方法,去除字符串开头或者结尾的空格

语法

str.strip([chars]);
  • chars – 移除字符串头尾指定的字符序列。

实例

str = "00000003210Runoob01230000000";
print(str.strip('0'))  # 去除首尾字符 0

str2 = "   Runoob      "   # 去除首尾空格
print(str2.strip())

#输出:
#3210Runoob0123
#Runoob

3、rstrip()方法,去除字符串结尾的空格

语法

str.rstrip([chars])

参数

  • chars – 指定删除的字符(默认为空格)

返回值

返回删除 string 字符串末尾的指定字符后生成的新字符串。

实例

str = "       this is string example....aaaaa!!!     "
print (str.rstrip())
str = "#######this is string example....aaaaa!!!######"
print (str.rstrip('#'))

#输出:
#       this is string example....aaaaa!!!
#######this is string example....aaaaa!!!

4、lstrip()方法,去除字符串开头的空格;

语法

str.lstrip([chars])

参数

  • chars --指定截取的字符。

返回值

返回截掉字符串左边的空格或指定字符后生成的新字符串。

实例

str = "         this is string example!!!     "
print( str.lstrip() )
str = "#########this is string example!!!#########"
print( str.lstrip('#') )

# 输出
# this is string example!!!     
# this is string example!!!#########

5、join()方法+split()方法,可以去除全部空格;

语法

str.join(sequence)

http://www.niftyadmin.cn/n/4799777.html

相关文章

安装memcache 时提示error while loading shared libraries: libevent-2.0解决办法

安装memcache 启动服务时出现 error while loading shared libraries: libevent-2.0.so.5: cannot open shared object file: No such file or directory >whereis libevent-2.0.so.5 libevent-2.0.so.5: /usr/local/lib/libevent-2.0.so.5 > ldd /usr/local/bin/memcach…

解决msvcr120.dll文件丢失问题(搞了半天,简直奔溃,最后完美解决)

我是在安装MySQL时提示缺少这个文件,搞了1太多,各种方法都试了。。。。。。 解决办法: 试了好多方法,都解决不了。 网上下载msvcr120.dll放到对应目录下失败 下载安装VC2013,微软官网的链接 https://www.microsoft.co…

android事件处理总结--dispatchTouchEvent

http://zhhx.blog.sohu.com/219275937.html 转载于:https://www.cnblogs.com/Tristan2012/archive/2012/11/28/2792980.html

eclipse、jdk、tomcat版本对应关系

不同版本的eclipse对jdk版本要求不一样,最高支持tomcat版本也不一样,下面是三者之间的对应关系。 Eclipse版本最低Java版本最高Tomcat版本Eclipse 4.8 (Photon)Java8Tomcat9.0Eclipse 4.7 (Oxygen)Java8Tomcat9.0Eclipse 4.6 (Neon)Java8Tomcat9.0Eclip…

JavaWeb错误汇总(持续更新)

建议 1、JSP工程名,路径,jsp文件名最好不要用中文命名。 2、编码格式统一设置为UTF-8格式。 错误汇总 1、404错误 错误描述: 解决办法: 1.把你要运行的文件名修改为index.jsp(不一定修改) 2.把有中文…

TCP粘包拆包基本解决方案

TCP粘包拆包基本解决方案参考文章: (1)TCP粘包拆包基本解决方案 (2)https://www.cnblogs.com/duan2/p/8858138.html (3)https://www.codeprj.com/blog/872a1a1.html 备忘一下。

HTML Img标签 src为网络地址无法显示图片问题解决(https)

HTML Img标签 src为网络地址无法显示图片问题解决(https)参考文章: (1)HTML Img标签 src为网络地址无法显示图片问题解决(https) (2)https://www.cnblogs.com/guozhaox…

Dockerfile执行命令报错The command 'binsh -c apt-get install -y git' returned a non-zero code 100解决

错误描述: 在Dockerfle里面执行apt-get update时出现错误,我这里时安装mysql时出现如下报错: 安装数据库的Dockerfile文件如下: FROM ubuntuMAINTAINER cwy# 将sources.list复制到镜像下的/etc/apt/下面,修改镜像源地…