How to use text strip() function?

后端 未结 2 488
执念已碎
执念已碎 2021-01-26 03:30

I can strip numerics but not alpha characters:

>>> text
\'132abcd13232111\'

>>> text.strip(\'123\')
\'abcd\'

Why the followi

相关标签:
2条回答
  • 2021-01-26 04:06

    Just to add a few examples to Jim's answer, according to .strip() docs:

    • Return a copy of the string with the leading and trailing characters removed.
    • The chars argument is a string specifying the set of characters to be removed.
    • If omitted or None, the chars argument defaults to removing whitespace.
    • The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped.

    So it doesn't matter if it's a digit or not, the main reason your second code didn't worked as you expected, is because the term "abcd" was located in the middle of the string.


    Example1:

    s = '132abcd13232111'
    print(s.strip('123'))
    print(s.strip('abcd'))
    

    Output:

    abcd
    132abcd13232111
    

    Example2:

    t = 'abcd12312313abcd'
    print(t.strip('123'))
    print(t.strip('abcd'))
    

    Output:

    abcd12312313abcd
    12312313
    
    0 讨论(0)
  • 2021-01-26 04:09

    The reason is simple and stated in the documentation of strip:

    str.strip([chars])
    
    Return a copy of the string with the leading and trailing characters removed. 
    The chars argument is a string specifying the set of characters to be removed.
    

    'abcd' is neither leading nor trailing in the string '132abcd13232111' so it isn't stripped.

    0 讨论(0)
提交回复
热议问题