python strip方法的坑

2021-10-03 05:41:40 字數 1319 閱讀 4373

str1=』』

if str1 is none的寫法是錯的,正確的寫法是

if str1 is 『』

>>

> str1=

''>>

> str1 is

none

false

吐了有木有啊~空字元居然不能用none來表示,而列表就能用none來表示,這是一點突破了我的認知的地方。

mark錯誤的方法

>>

>

str=

''">>

>str1 is

none

>

false

結論:"" is not none!

當字串有單個空格的時候,用split方法來分割會非常方便,但是如果字串物件有兩個連續的空格時,就會產生bug:

str2=

'abc bcd efg'

list1=str2.split(

' ')

list1

>>

>

['abc'

,'bcd',''

,'efg'

]

看到沒,我真是暈了,居然會帶乙個空字元,所以我又調了特別久才把這個東西給研究出來.再講乙個更重要的,如果字串開頭或者結尾有空格,會導致空格對應處各生成乙個空字串!

>>

> str3=

' abc '

>>

> list3=str3.split(

' ')

>>

> list3[''

,'abc',''

]

8廢話了,直接上**

>>

> str1=

" abc "

>>

> str1.strip(

)'abc'

>>

> str2=str1.strip(

)>>

> str2

'abc'

>>

> str1

' abc '

>>

>

strip方法是不原地轉換的,需要用str2=str1.strip()接住返回值,莫搞錯了!

寫到這裡先結束啦,放出自己辛辛苦苦寫了一下午的成果

Python strip 函式踩坑

s.strip chars none strip 函式用於去除字串首尾的空格,當 chars 不為 none 時,則刪除字串首尾的 chars 中的字元。當 chars none 時,去除首尾空格,沒啥好說的,我們來看 chars 不為 none 時的情況。str abc123abc print s...

js toFixed 方法的坑

做專案的時候,需要保留兩位小數,本以為用tofixed 完美,然並卵 2.35.tofixed 1 2.4 2.335.tofixed 2 2.33 2.3335.tofixed 3 2.333 保留小數 四捨五入 data 要保留的數,val 保留的位數 function tofixed data...

python strip 的正規表示式版本

寫乙個函式,它接受乙個字串,做的事情和 strip 字串方法一樣。如果只傳入了要去除的字串,沒有其他引數,那麼就從該字串首尾去除空白字元。否則,函式第二個引數指定的字元將從該字串中去除。import re def restrip text,param mo re.compile r str para...