Python 从列表项中去除字符
我正在尝试从存储在矩阵中的时间戳中去掉一些字符(如果你愿意,也可以把它看作是一个列表的列表)。我想提取这个项目,并在去掉不需要的字符后将其用作文件名(原始列表中的内容应该保持不变)。我对去掉字符和其他字符串操作比较熟悉,平时也经常用,但这次我遇到了麻烦,不知道怎么回事,几乎试过所有的方法。我想得到的是 '2011092723492',而不是原来的 '2011.09.27 23:49 2'。在这个例子中,只是想把 ':' 替换掉,方便一些。我是不是漏掉了什么?
for x in FILEmatrix:
flnm = str(x[4]) # or just 'x[4]' doesn't matter it is a string for sure
print type(flnm) # <type 'str'> OK, not a list or whatever
print 'check1: ', flnm # '2011.09.27 23:49 2'
flnm.strip(':') # i want to get '2011092723492', ':' for starters, but...
print 'check2: ', flnm # nothing... '2011.09.27 23:49 2'
string.strip(flnm,':')
print 'check3: ', flnm # nothing... '2011.09.27 23:49 2'
flnm = flnm.strip(':')
print 'check4: ', flnm # nothing... '2011.09.27 23:49 2'
flnm.replace(':', '')
print 'check5: ', flnm # nothing... '2011.09.27 23:49 2'
非常感谢!
5 个回答
2
在Python中,通常有不止一种方法来完成同一件事。
不过首先要说明的是,strip
的工作方式可能和你想的不同。
>>> flnm = '2011.09.27 23:49 2'
>>> flnm.strip('2') # notice that strip only affects the ends of the string
'011.09.27 23:49 '
你可以把那些没有被排除的字符连接起来。
rejected = ' :.'
flnm = ''.join(c for c in flnm if c not in rejected)
或者只连接数字字符。
flnm = ''.join(c for c in flnm if c.isdigit())
还可以连续调用多次string.replace
。
flnm = flnm.replace(' ','').replace('.','').replace(':','')
或者使用re.sub
。
import re
flnm = re.sub('\D', '', flnm)
因为字符串是不可变的,所以一定要把结果重新赋值给flnm
。
补充:
还有更多的方法可以做到这一点!
使用reduce
(来自Ivan的回答):
rejected = ' :.'
flnm = reduce(lambda a, d: a.replace(d,''), rejected, flnm)
使用translate
(来自oxtopus的回答):
rejected = ' :.'
flnm = flnm.translate(None, rejected)
我更喜欢oxtopus使用的translate
,因为它是最简单明了的。
3
试试这个:
import re
flnm = re.sub('[^0-9]', '', flnm)
3
这不是str.strip()
的作用,也不是它的工作方式。字符串是不可变的,所以这个方法会返回一个新的结果。
flnm = flnm.replace(':', '')
如果你想去掉其他字符,可以重复这个操作。