Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python字符串去空格

作者:此甥孓狠善良   发布日期:2025-10-10   浏览:46

# 示例代码:去除字符串中的空格

# 使用 strip() 方法去除字符串两端的空格
s = "   hello world   "
s_strip = s.strip()
print(f"使用 strip() 方法: '{s_strip}'")  # 输出: 'hello world'

# 使用 lstrip() 方法去除字符串左边的空格
s_lstrip = s.lstrip()
print(f"使用 lstrip() 方法: '{s_lstrip}'")  # 输出: 'hello world   '

# 使用 rstrip() 方法去除字符串右边的空格
s_rstrip = s.rstrip()
print(f"使用 rstrip() 方法: '{s_rstrip}'")  # 输出: '   hello world'

# 使用 replace() 方法去除字符串中所有的空格
s_replace = s.replace(" ", "")
print(f"使用 replace() 方法: '{s_replace}'")  # 输出: 'helloworld'

解释说明:

  1. strip():去除字符串两端的空格(包括制表符、换行符等空白字符)。
  2. lstrip():仅去除字符串左边的空格。
  3. rstrip():仅去除字符串右边的空格。
  4. replace(" ", ""):将字符串中的所有空格替换为空字符串,从而达到去除所有空格的效果。

上一篇:python range(10)

下一篇:python回车符号

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站