How to remove leading and trailing zeros in a string? Python

后端 未结 6 1978
庸人自扰
庸人自扰 2020-11-28 06:42

I have several alphanumeric strings like these

listOfNum = [\'000231512-n\',\'1209123100000-n00000\',\'alphanumeric0000\', \'000alphanumeric\']
6条回答
  •  有刺的猬
    2020-11-28 07:10

    Assuming you have other data types (and not only string) in your list try this. This removes trailing and leading zeros from strings and leaves other data types untouched. This also handles the special case s = '0'

    e.g

    a = ['001', '200', 'akdl00', 200, 100, '0']
    
    b = [(lambda x: x.strip('0') if isinstance(x,str) and len(x) != 1 else x)(x) for x in a]
    
    b
    >>>['1', '2', 'akdl', 200, 100, '0']
    
    

提交回复
热议问题