Python 中的 strip() 函数

17 Mar 2025 | 4 分钟阅读

strip() 功能是 Python 的一个内置库功能。它用于通过删除传递给 strip() 函数的前导和尾随空格、字符和符号来返回原始字符串的副本。换句话说,一组字符作为参数传递给 Python 字符串 strip() 函数,然后该函数会删除字符串左右两端的字符。如果 strip() 函数没有传递参数,则默认删除字符串开头和结尾的空格。

strip() function in Python

Python 中的 strip() 函数

语法

参数

  • strip,或 "chars":这是一个可选参数。因此,如果程序员不传递任何参数,strip() 函数将删除字符串的开头和结尾的空格。
  • 如果将给定边界的排列传递给 strip() 功能,它将从第一个字符串中删除字符或图像。
  • 返回值:通过从原始字符串中删除一组字符或空格,它会返回一个副本。

使用 strip() 函数从给定字符串中删除字符或符号

让我们看一个示例,通过在 Python 中删除给定字符串的前导或尾随字符来执行 strip() 函数。

Strip.py

输出

Given string is:    $$$$$  No. 1 Welcome to JAVATPOINT!! No. 1 $$$ 
 After removing the set of characters:  Welcome to JAVATPOINT

 Given string is   1 11 111 111 1111 Learn Python Programming Tutorial 1111 111 11 1
 Stripping 1 from both ends of the string using strip ('1') function   1 11 111 111 1111 Learn Python 
Programming Tutorial 1111 111 11 1

 Given string is =  ++++++Python Programming Tutorial****** $$$$$
 Stripping the '+', '*' and '$' symbols on both sides of the string is =  Python Programming Tutorial

使用 strip() 函数从给定字符串中删除空格

让我们看一个示例,通过在 Python 中删除给定字符串的前导或尾随空格来执行 strip() 函数。

Strip2.py

输出

Given string is:     Welcome to the World!
 After removing whitespaces from an original string:  Welcome to the World!
 Given string is:               Learn    Python    programming
 After removing whitespaces from an original string:  Learn    Python    programming

在上面的程序中,我们使用 strip() 函数来删除给定字符串开头和结尾的空格,但它不会删除字符串之间的空格。

从用户那里获取任何字符串并使用 strip() 函数删除任何字符或符号的程序

Prog.py

输出

Enter the string *** $$ Welcome to JavaTpoint. Learn Python programming !!! &&
 Your string is  *** $$ Welcome to JavaTpoint. Learn Python programming !!! &&
 Enter any character or symbol that you don't want to see in the string * $ Wel ! &
 After performing the strip() function, 
 Your string is  come to JavaTpoint. Learn Python programming

为什么要使用 Python strip() 函数?

使用 Python strip 函数的原因如下:

  • 它有助于根据传递给 strip() 功能的字符,从原始字符串的开头和结尾删除字符。
  • 如果用户未向其传递任何字符,则 strip 函数默认会删除字符串两端的空白字符。
  • 如果字符串开头或结尾没有空格,它会返回原始字符串而不会进行任何更改。
  • 如果传入的字符与原始字符串不匹配,strip 功能会返回原始字符串。

结论

在上一节中,我们学习了 Python 库的 strip() 函数。它是一个 strip() 功能,用于删除原始字符串的开头和结尾的字符或空格。但是,如果用户未向其传递任何字符,strip() 函数仅删除原始字符串开头和结尾的空格。


下一主题梯度下降算法