Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

python - 如何修剪空白?(How do I trim whitespace?)

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

(是否有Python函数可以从字符串中修剪空白(空格和制表符)?)

Example: \t example string\texample string

(示例: \t example string\texample string)

  ask by Chris translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Whitespace on both sides:

(两侧的空格:)

s = "   a string example  "
s = s.strip()

Whitespace on the right side:

(右侧的空格:)

s = s.rstrip()

Whitespace on the left side:

(左侧的空白:)

s = s.lstrip()

As thedz points out, you can provide an argument to strip arbitrary characters to any of these functions like this:

(正如thedz所指出的,您可以提供一个参数来将任意字符剥离到以下任何函数中,如下所示:)

s = s.strip(' 

')

This will strip any space, \t , \n , or \r characters from the left-hand side, right-hand side, or both sides of the string.

(这将从字符串的左侧,右侧或两侧去除所有空格, \t\n\r字符。)

The examples above only remove strings from the left-hand and right-hand sides of strings.

(上面的示例仅从字符串的左侧和右侧删除字符串。)

If you want to also remove characters from the middle of a string, try re.sub :

(如果您还想从字符串中间删除字符,请尝试re.sub :)

import re
print re.sub('[s+]', '', s)

That should print out:

(那应该打印出来:)

astringexample

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...