python字符串去掉空行
There are various ways to remove spaces from a string in Python. This tutorial is aimed to provide a short example of various functions we can use to remove whitespaces from a string.
在Python中,有多种方法可以从字符串中删除空格。 本教程旨在提供各种示例的简短示例,我们可以使用这些示例来删除字符串中的空格。
Python String is immutable, so we can’t change its value. Any function that manipulates string value returns a new string and we have to explicitly assign it to the string, otherwise, the string value won’t change.
Python String是不可变的,因此我们无法更改其值。 任何操作字符串值的函数都将返回一个新字符串,我们必须将其显式分配给该字符串,否则,字符串值将不会更改。
Let’s say we have an example string defined as:
假设我们有一个示例字符串定义为:
s = ' Hello World From Pankaj \t\n\r\tHi There '
This string has different types of whitespaces as well as newline characters.
该字符串具有不同类型的空格以及换行符。
Let’s have a look at different functions to remove spaces.
让我们看一下删除空格的不同功能。
Python String strip() function will remove leading and trailing whitespaces.
Python String strip()函数将删除前导和尾随空格。
>>> s.strip()
'Hello World From Pankaj \t\n\r\tHi There'
If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
如果只想删除前导或尾随空格,请改用lstrip()或rstrip()函数。
We can use replace() to remove all the whitespaces from the string. This function will remove whitespaces between words too.
我们可以使用replace()从字符串中删除所有空格。 此功能也将删除单词之间的空格。
>>> s.replace(" ", "")
'HelloWorldFromPankaj\t\n\r\tHiThere'
If you want to get rid of all the duplicate whitespaces and newline characters, then you can use join() function with string split() function.
如果要消除所有重复的空格和换行符,则可以将join()函数与字符串split()函数一起使用 。
>>> " ".join(s.split())
'Hello World From Pankaj Hi There'
If you want to get rid of all the whitespaces as well as newline characters, you can use string translate() function.
如果要摆脱所有空格和换行符,可以使用字符串translate()函数 。
>>> import string
>>> s.translate({ord(c): None for c in string.whitespace})
'HelloWorldFromPankajHiThere'
We can also use a regular expression to match whitespace and remove them using re.sub()
function.
我们还可以使用正则表达式来匹配空格,并使用re.sub()
函数将其删除。
import re
s = ' Hello World From Pankaj \t\n\r\tHi There '
print('Remove all spaces using RegEx:\n', re.sub(r"\s+", "", s), sep='') # \s matches all white spaces
print('Remove leading spaces using RegEx:\n', re.sub(r"^\s+", "", s), sep='') # ^ matches start
print('Remove trailing spaces using RegEx:\n', re.sub(r"\s+$", "", s), sep='') # $ matches end
print('Remove leading and trailing spaces using RegEx:\n', re.sub(r"^\s+|\s+$", "", s), sep='') # | for OR condition
Output:
输出:
Remove all spaces using RegEx:
HelloWorldFromPankajHiThere
Remove leading spaces using RegEx:
Hello World From Pankaj
Hi There
Remove trailing spaces using RegEx:
Hello World From Pankaj
Hi There
Remove leading and trailing spaces using RegEx:
Hello World From Pankaj
Hi There
Reference: StackOverflow Question
参考: StackOverflow问题
翻译自: https://www.journaldev.com/23763/python-remove-spaces-from-string
python字符串去掉空行