2011-09-29 188 views
0

我试图从存储在矩阵中的时间戳(或列表,如果你想要)删除字符。我想提取该项目,并在剥离不需要的字符后使用它作为文件名(它应该在原始列表中保持不变)。我对通常使用它的剥离和其他字符串操作非常熟悉,但是现在我用这个来填充,我不知道发生了什么,我尝试了几乎所有的东西。我想获得'2011092723492'而不是原来的'2011.09.27 23:49 2'。在这个例子中只是':'被替换,以使它更容易。我错过了什么吗?:python从列表项中删除字符

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' 

非常感谢!

+0

另请参阅:http:// stackoverflow。com/questions/7588511/format-a-datetime-into-a-string-with-milliseconds –

回答

3

这不是str.strip()所做的,这不是它的工作原理。字符串是不可变的,所以结果从方法返回。

flnm = flnm.replace(':', '') 

重复您想删除的其他字符。

+0

非常感谢!有用! 我开始看到了。到目前为止,我已经对readline()中的数据执行了剥离操作,所以可能会有所不同。但readline()中的字符串与列表中的字符串有什么区别? – tookanstoken

+0

绝对没有。 –

3

试试这个:

import re 
flnm = re.sub('[^0-9]', '', flnm) 
+0

谢谢,这工作也很好。 – tookanstoken

0
res = reduce(lambda a, d: a.replace(d,''),[':','.',' '],flnm) 
2

这是非常快的(如果你想要去除从字符串那些已知非字母字符):

flnm.translate(None, ' .:') 
+0

+1。适合正确工作的正确工具。 –

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

编辑:

更多的方式来做到这一点!

Using reduce(伊万的回答):

rejected = ' :.' 
flnm = reduce(lambda a, d: a.replace(d,''), rejected, flnm) 

Using translate(从oxtopus的答案):

rejected = ' :.' 
flnm = flnm.translate(None, rejected) 

我喜欢oxtopus的使用translate,因为它是最直接的。