python从列表项中剥离字符

时间:2011-09-29 21:34:45

标签: python string list strip

我正在尝试从存储在矩阵(或列表列表中)的时间戳中删除字符(如果需要)。我想提取项目并在剥离不需要的字符后将其用作文件名(它应该在原始列表中保持不变)。我非常熟悉我经常使用的剥离和其他字符串操作,但现在我坚持这个,我不知道发生了什么,我几乎尝试过所有事情。我想得到'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 个答案:

答案 0 :(得分:3)

这不是str.strip()的作用,而不是它的运作方式。字符串是不可变的,因此结果从方法返回。

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

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

答案 1 :(得分:3)

试试这个:

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

答案 2 :(得分:2)

这非常快(如果你想从字符串中删除那些已知的非alpha字符):

flnm.translate(None, ' .:')

答案 3 :(得分: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(来自Ivan的回答):

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

Using translate(来自oxtopus的回答):

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

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

答案 4 :(得分:0)

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