用于从字符串中修剪空白的 Python 程序

要理解这个例子,你应该具备以下 Python 编程 主题的知识


示例 1:使用 strip()

my_string = " Python "

print(my_string.strip())

输出

Python

strip() 从字符串中删除开头和结尾的字符,包括空格。

但是,如果字符串中有像 '\n' 这样的字符,并且您只想删除空格,则需要像以下代码所示在 strip() 方法上明确指定它。

my_string = " \nPython "

print(my_string.strip(" "))

输出


Python

要了解更多信息,请访问 Python 字符串 strip()


示例 2:使用正则表达式

import re

my_string  = " Hello Python "
output = re.sub(r'^\s+|\s+$', '', my_string)

print(output)

输出

Hello python

在正则表达式中,\s 表示空格,\ 是或运算。+ 表示其左侧模式出现一次或多次。

Python 正则表达式 了解更多关于正则表达式的信息。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战