我正在學習 Python。特別是,我閱讀了 python 字串的 split 方法,并了解到默認分隔符split是空格。所以我了解以下內容是如何作業的:
text = 'Hello World'
print(text.split()) #this should print ['Hello', 'World'] which it does
上面程式在 Python3.6 中的輸出符合['Hello', 'World']預期,因為在上面的字串變數text中我們有空格。
但后來我嘗試了以下示例:
text = 'Hello\nWorld'
print(text.split()) #this should print ['Hello\nWorld'] but it doesn't
上面的實際輸出是:
['Hello', 'World'] #this shouldn't happen because there is no whitespace in text
而上述的預期輸出是:
['Hello\nWorld'] #this should happen because there is no whitespace in text
如您所見,由于之間沒有空格'Hello','World'因此輸出應該是['Hello\nWorld']因為\n不是空格,而空格是split方法的默認分隔符。
這里發生了什么。
uj5u.com熱心網友回復:
如果 sep 未指定或為 None,則應用不同的拆分演算法:連續空格的運行被視為單個分隔符,如果字串具有前導或尾隨空格,則結果將在開頭或結尾不包含空字串。
制表\t符 ( )、換行符 ( \n)、空格等。它們都算作空白字符,因為從技術上講,它們都具有相同的用途。把東西隔開。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/448809.html
標籤:Python 细绳 分裂 python-3.6
上一篇:將char型別轉換為字串
