关于Python去除字符串中空格的方法总结

作者:黄佳俊、 时间:2022-05-07 17:27:11 

需要将字符串中的空格去掉的情况,可以使用下面几种解决方法:

1、strip()方法:该方法只能把字符串头和尾的空格去掉,但是不能将字符串中间的空格去掉。

s=' This is a demo '

print(s.strip())

结果:"This is a demo"

lstrip():该方法只能把字符串最左边的空格去掉。

s=' ! This is a demo '
l='!'
print(s.lstrip()+l)

结果:"! This is a demo !"

rstrip():该方法只能把字符串最右边的空格去掉。

s=' ! This is a demo '
l='!'
print(s.rstrip()+l)

结果:"! This is a demo!"

2.replace(m,n)方法:将字符串里面的m替换为n。

#将字符串中所有的空格删除
s=' This is a demo '
print(s.replace(' ',''))

结果:"Thisisademo"

3.split(s,num)方法:split(s,num)

#使用join()方法将字符串中所有的空格删除
s=' This is a demo '
print(''.join(s.split()))

结果:"Thisisademo"

其中,join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。

格式如下:

s.join(sequence)

元素之间的分隔符是s,sequence是要连接的元素序列。

补充:split()、join()方法同时使用

作用:删除字符串里面所有的空格

>>> str = '     h    e    l    l     '
>>> str1 = str.split()
>>> str2 = ''.join(str1)
>>> print(str2)
hell
>>>

来源:https://blog.csdn.net/weixin_48419914/article/details/120771796

标签:python,字符串,空格
0
投稿

猜你喜欢

  • 在函数间不能传递32个以上参数的疑难问题

    2008-12-31 13:31:00
  • 使用Python获取CPU、内存和硬盘等windowns系统信息的2个例子

    2023-08-26 23:12:32
  • Django实现快速分页的方法实例

    2022-12-27 06:02:30
  • 基于python3监控服务器状态进行邮件报警

    2022-05-05 05:25:39
  • PHP设计模式中的命令模式

    2023-05-27 21:13:43
  • Python编程pytorch深度卷积神经网络AlexNet详解

    2022-02-18 10:28:40
  • python sorted方法和列表使用解析

    2021-07-09 05:32:41
  • SQL Server数据库查询优化的常用方法总结

    2008-12-10 14:43:00
  • pandas使用fillna函数填充NaN值的代码实例

    2023-09-29 05:51:48
  • Python抓新型冠状病毒肺炎疫情数据并绘制全国疫情分布的代码实例

    2022-10-11 23:14:40
  • python 邮件检测工具mmpi的使用

    2022-03-18 04:56:45
  • Python时间和字符串转换操作实例分析

    2023-04-15 22:58:08
  • 基于Python计算圆周率pi代码实例

    2021-03-06 05:13:17
  • python对配置文件.ini进行增删改查操作的方法示例

    2023-10-25 05:56:13
  • IE6下的CSS BUG枚举

    2010-06-11 10:45:00
  • Python Playwright的使用详解

    2021-10-10 03:30:44
  • MySQL 表字段属性

    2011-09-10 16:01:01
  • 对Python获取屏幕截图的4种方法详解

    2023-11-19 09:45:41
  • 利用OBJECT_DEFINITION函数来代码存档

    2009-01-20 15:34:00
  • 定格动画浅析(一)

    2009-07-30 12:50:00
  • asp之家 网络编程 m.aspxhome.com