Python中字符串的split()方法和split(‘ ’)有什么区别

首先我们来看一下split()方法的官方介绍:

str.split([sep[, maxsplit]])

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

返回一个包含字符串单词的列表,并且使用sep作为分隔字符串。如果指定了maxsplit这个参数,则只会切割maxsplit次(因此,这个生成的列表最多只有maxsplit+1个元素),如果maxsplit这个参数没有指定或者是-1,这时分割次数不会有限制(所有可能的分割都会发生)。

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, ‘1,,2’.split(‘,’) returns [‘1’, ”, ‘2’]). The sep argument may consist of multiple characters (for example, ‘1<>2<>3’.split(‘<>’) returns [‘1’, ‘2’, ‘3’]). Splitting an empty string with a specified separator returns [”].

如果sep分隔子串这个参数指定了,连续的分隔符不会被当做一个分隔符使用,而是被分割成为一个空的字符串(举个例子,‘1,,2’.split(‘,’)这个表达式的返回值是[‘1’, ”, ‘2’])。sep分隔子串可以是由多个字符组成的(例如:‘1<>2<>3<>’.split(‘<>’)表达式的返回值是[‘1’, ‘2’, ‘3’])。用一个指定的分隔子串去分割一个空字符串会返回一个[”]。

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这个分隔子串参数未指定或者是None,这个时候会有一种新的切割情况出现:它会将连续的空白字符当做一个单一的分隔符,并且结果里面的最开始的元素和最末尾的元素不会包含空字符串,当然,使用None作为分隔子串去分割一个空字符串或者一个包含连续空格符的字符串会返回[]。

For example, ’ 1 2 3 ‘.split() returns [‘1’, ‘2’, ‘3’], and ’ 1 2 3 ‘.split(None, 1) returns [‘1’, ‘2 3 ‘].

举个例子,’1 2 3 ‘.split()的返回值是[‘1’, ‘2’, ‘3’],’1 2 3 ‘.split(None, 1)的返回值是[‘1’, ‘2 3 ‘]。

相信大家看完上面的官方介绍应该就能理解这两的区别了吧。

猜你喜欢

转载自blog.csdn.net/june_young_fan/article/details/79841865