From c52919b9ec6b3c945b30730a786af15ad9507ca3 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sat, 8 Jun 2019 14:21:19 +0530 Subject: [PATCH] Add new snippet: Splitsies Resolves https://github.com/satwikkansal/wtfpython/issues/80 --- README.md | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 05bbe15..2947bb7 100644 --- a/README.md +++ b/README.md @@ -207,6 +207,44 @@ Makes sense, right? --- +### ▶ Splitsies ^ + +```py +>>> 'a'.split() +['a'] + +# is same as +>>> 'a'.split(' ') +['a'] + +# but +>>> len(''.split()) +0 + +# isn't the same as +>>> len(''.split(' ')) +1 +``` + +#### 💡 Explanation: + +- It might appear at first that the default seperator for split is a single space `' '`, but as per the [docs](https://docs.python.org/2.7/library/stdtypes.html#str.split), + > 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 `[]`. + > 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']`). Splitting an empty string with a specified separator returns `['']`. +- Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear, + ```py + >>> ' a '.split(' ') + ['', 'a', ''] + >>> ' a '.split() + ['a'] + >>> ''.split(' ') + [''] + ``` + +--- + + + ### ▶ Time for some hash brownies! 1\. @@ -702,7 +740,7 @@ SyntaxError: invalid syntax --- -### ▶ Strings and the backslashes\ +### ▶ Strings and the backslashes\ ^ **Output:** ```py