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
165 views
in Technique[技术] by (71.8m points)

string - How does .split() work? - Python

In the following examples, I am splitting an empty string by a space. However, in the first example I explicitly used a space and in the second example, I didn't. My understanding was that .split() and .split(' ') were equivalent.

Why do these two examples give different outputs?

In [1]: "".split(' ')
Out[1]: ['']

In [2]: "".split()
Out[2]: []
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

From the python's documentation -

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

Sep is the separator. What it says is if we don't pass anything to split, whitespaces are considered as separators, it will apply a different algorithm to split strings and will return us a [] but since you passed a sep, it will not apply this algorithm


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

...