python-基础语法-使用sprip()和split()处理空白字符

0.摘要

在数据输入的时候,考虑的易读性,往往会加上大量的空白字符调整间距。但在使用数据时候,需要恰当地处理掉空白字符。

本文主要介绍,使用sprip()和split()处理空白字符的方法。

1.String strip()方法

官方解释:

    S.strip([chars]) -> str

    Return a copy of the string S with leading and trailing whitespace removed.
    If chars is given and not None, remove characters in chars instead.

翻译:

若chars为未给定,则删除字符串头尾的空白字符,包括\r,\t\,\n和空格;

若chars给定,则删除字符串头尾,位于chars中的字符。注意,无顺序要求。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

str1 = '\n\n\r\t   hello,world!  \t  '
print(str1.strip())
#result:hello,world!

str2 = "1024 grams potato convert to Calories is equel to 2048"
print(str2.strip('0123456789'))
#result: grams potato convert to Calories is equel to

str3 = "1024 grams potato convert to Calories is equel to 2048"
print(str3.strip('0123456789 '))
#result:grams potato convert to Calories is equel to

注意,这里str2和str3的处理方式有细微差别:

str2.strip('0123456789')中没有包含空格字符;
str3.strip('0123456789 ')中包含了空格字符;

所以,在最后的输出中,str3处理了空格字符,而str2没有;

另外,strip()方法还有两个变体:

S.lstrip(chars)       删除s字符串中开头处,位于 chars删除序列的字符

S.rstrip(chars)      删除s字符串中结尾处,位于 chars删除序列的字符

2.String split()方法

Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则仅分隔 num 个子字符串.

S.split(sep=None, maxsplit=-1) -> list of strings
  • sep -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
  • maxsplit -- 分割次数。
s = 'string1 string2  string3  \n string4'
print(s.split())
print(s.split(' '))
print(s.split(sep=None,maxsplit=3))

结果:

注意,如果指定了sep为一个空格,那么split()将只按照一个空格进行分割。

猜你喜欢

转载自blog.csdn.net/qq_17753903/article/details/82531711