[Python] python 的 strip() 是拿掉什麼字元?

[Python] python 的 strip() 是拿掉什麼字元?

python 的字串可以呼叫 strip() 函式來拿掉字串左右的空白字元,

這件事很簡單明瞭,但最近有個需求是除了拿掉空白字元外,還要拿掉 “.” 這個字元…

這樣的話,就得知道空白字元到底包含哪些東西了~

 

python 的官方文件上只寫說會拿掉 whitespace,但沒有指明是哪些字元

string 的文件上,是有另外一部分指明了 string.whitespace 指的是:

string.whitespace

A string containing all characters that are considered whitespace. On most systems this includes the characters space, tab, linefeed, return, formfeed, and vertical tab.

 

但是,””.strip() 用到的 whitespaces 跟 string.whitespace 用到的是一樣的字元嗎?

最乾脆的方法還是去查 python 的 source code…

最後在 stropmodule.c 的 do_strip() 函式裡,終於找到了答案:

    i = 0;
if (striptype != RIGHTSTRIP) {
while (i < len && isspace(Py_CHARMASK(s[i]))) {
i++;
}
}
j = len;
if (striptype != LEFTSTRIP) {
do {
j--;
} while (j >= i && isspace(Py_CHARMASK(s[j])));
j++;
}

 

這邊用到的是 C 的 isspace() 函式,因此結果確實是:

isspace()

checks for white-space characters. In the “C” and “POSIX” locales, these are: space, form-feed (‘\f’), newline (‘\n’), carriage return (‘\r’), horizontal tab (‘\t’), and vertical tab (‘\v’). 

 

回到我最一開始的問題,想要移掉 “.” 加上所有的空白字元,

那就是 “string_to_strip”.strip(‘ .\f\n\r\t\v’) 就可以囉~

 

(本頁面已被瀏覽過 1,240 次)

One thought on “[Python] python 的 strip() 是拿掉什麼字元?

  1. 謝謝你的追蹤分享,我會想用 string.whitespace,不知道你的看法如何?
    import string
    ‘tn.dddjajan.’.strip(”.join([string.whitespace, ‘.’]))
    版主回覆:(09/19/2014 04:00:26 PM)
    可以的喔~
    不過其實這邊也只有兩個字串要相加,
    我大概會用 ‘tn.dddjajan.’.strip(string.whitespace + ‘.’)
    不過效果都是一樣的啦~ 🙂

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料