您的位置:首页 > 编程语言 > Python开发

Python中一道关于字符串分割的题目

2017-12-05 19:57 447 查看
Python中一道字符串题目:

(面试题)给定一个字符串aStr,返回使用空格或者'\t'分割后的倒数第二个子串


例如

testStr = 'I have \t one \tdream!'
resultStr = testStr.split()
print(resultStr)
print(resultStr[-2])


常用分割字符串的方法split(),查看split()方法的源码

def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
"""
S.split(sep=None, maxsplit=-1) -> list of strings

Return a list of the words in S, using sep as the
delimiter string.  If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are
removed from the result.
"""
return []


其中这句话If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.当sep任何参数不给时将默认以任何空格和空白分割,而tab就是4个空格,因而直接用split()方法就可以了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 面试题