How do I trim whitespace?

2019-01-01 06:08发布

Is there a Python function that will trim whitespace (spaces and tabs) from a string?

Example: \t example string\texample string

14条回答
路过你的时光
2楼-- · 2019-01-01 06:26

Python trim method is called strip:

str.strip() #trim
str.lstrip() #ltrim
str.rstrip() #rtrim
查看更多
春风洒进眼中
3楼-- · 2019-01-01 06:26

(re.sub(' +', ' ',(my_str.replace('\n',' ')))).strip()

This will remove all the unwanted spaces and newline characters. Hope this help

import re
my_str = '   a     b \n c   '
formatted_str = (re.sub(' +', ' ',(my_str.replace('\n',' ')))).strip()

This will result :

' a      b \n c ' will be changed to 'a b c'

查看更多
听够珍惜
4楼-- · 2019-01-01 06:32

This will remove all whitespace and newlines from both the beginning and end of a string:

>>> s = "  \n\t  \n   some \n text \n     "
>>> re.sub("^\s+|\s+$", "", s)
>>> "some \n text"
查看更多
唯独是你
5楼-- · 2019-01-01 06:36

If using Python 3: In your print statement, finish with sep="". That will separate out all of the spaces.

EXAMPLE:

txt="potatoes"
print("I love ",txt,"",sep="")

This will print: I love potatoes.

Instead of: I love potatoes .

In your case, since you would be trying to get ride of the \t, do sep="\t"

查看更多
萌妹纸的霸气范
6楼-- · 2019-01-01 06:37

Whitespace includes space, tabs and CRLF. So an elegant and one-liner string function we can use is translate.

' hello apple'.translate(None, ' \n\t\r')

OR if you want to be thorough

import string
' hello  apple'.translate(None, string.whitespace)
查看更多
梦该遗忘
7楼-- · 2019-01-01 06:37
    something = "\t  please_     \t remove_  all_    \n\n\n\nwhitespaces\n\t  "

    something = "".join(something.split())

output: please_remove_all_whitespaces

查看更多
登录 后发表回答