获取到的字符串,存在不明原因的换行和空格,如何整合成一个单句?

1. 去空格

1.1 strip()首尾空格

该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

语法:

str.strip([chars])
# -*- coding: utf-8 -*-
# @Time    : 2021/3/17  13:55
# @Author  : 天泽岁月
# @File    : test.py
# @Software: PyCharm
# @Describe: 
# -*- encoding:utf-8 -*-
# 演示了只要头尾包含有指定字符序列中的字符就删除

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

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

在这里插入图片描述

1.2 replace()中间空格

把字符串中的 old(旧字符串) 替换成 new(新字符串)
如果指定第三个参数max,则替换不超过 max 次。

语法:

str.replace(old, new[, max])

参数:

old – 将被替换的子字符串。
new – 新字符串,用于替换old子字符串。
max – 可选字符串, 替换不超过 max 次

  • replace()实例:
str = 'this1 is2 string example....wow!!! this3 is4 really is5 string'
print(str.replace("is", "was"))
print(str.replace("is", "was", 4))

在这里插入图片描述

  • 去中间空格实例:
# -*- coding: utf-8 -*-
# @Time    : 2021/3/17  13:55
# @Author  : 天泽岁月
# @File    : test.py
# @Software: PyCharm
# @Describe: 
# -*- encoding:utf-8 -*-

# 这里的1111代表空格
str = '''     《
            人民日报
            》                  (
             2017年09月26日

              04
              版)

                             》    '''
print(str.strip().replace(' ', '')) # 同时去掉首尾+中间空格

在这里插入图片描述

使用 .strip() 只能够去除字符串首尾的空格,不能够去除中间的空格
所以需要使用 .replace(’ ', ‘’) 来替换空格项。

2. 去换行

2.1 replace()

# -*- coding: utf-8 -*-
# @Time    : 2021/3/17  13:55
# @Author  : 天泽岁月
# @File    : test.py
# @Software: PyCharm
# @Describe: 
# -*- encoding:utf-8 -*-

# 这里的1111代表空格
str = '''     《
            人民日报
            》                  (
             2017年09月26日

              04
              版)

                             》    '''

print(str.strip().replace(' ', '').replace('\n', ''))

在这里插入图片描述
这里已经去掉了所有空格。


若是发现并不能达到效果,原因:

在python中存在继承了 回车符\r 和 换行符\n 两种标记,\r和\n 都是以前的那种打字机传承来的。

  • \r 代表回车,也就是打印头归位,回到某一行的开头。
  • \n代表换行,就是走纸,下一行。
  • linux只用\n换行,win下用\r\n表示换行。

结论:

在去除换行时,需要同时去除两者才行,即再加上 .replace(’\r’, ‘’)

print(str.strip().replace(' ', '').replace('\n', '').replace('\r', ''))

效果同样:
在这里插入图片描述

知识点复习(菜鸟教程)

  1. Python strip()方法
  2. Python replace()方法
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐