Python去除字符串两端空格的方法
目的
获得一个首尾不含多余空格的字符串
方法
可以使用字符串的以下方法处理:
string.lstrip(s[,chars])
Returnacopyofthestringwithleadingcharactersremoved.IfcharsisomittedorNone,whitespacecharactersareremoved.IfgivenandnotNone,charsmustbeastring;thecharactersinthestringwillbestrippedfromthebeginningofthestringthismethodiscalledon.
string.rstrip(s[,chars])
Returnacopyofthestringwithtrailingcharactersremoved.IfcharsisomittedorNone,whitespacecharactersareremoved.IfgivenandnotNone,charsmustbeastring;thecharactersinthestringwillbestrippedfromtheendofthestringthismethodiscalledon.
string.strip(s[,chars])
Returnacopyofthestringwithleadingandtrailingcharactersremoved.IfcharsisomittedorNone,whitespacecharactersareremoved.IfgivenandnotNone,charsmustbeastring;thecharactersinthestringwillbestrippedfromthebothendsofthestringthismethodiscalledon.
具体的效果如下:
In[10]:x=' Hi,Jack! '
In[11]:print'|',x.lstrip(),'|',x.rstrip(),'|',x.strip(),'|' |Hi,Jack! | Hi,Jack!|Hi,Jack!|