Pythonic String Manipulation

时间:2013-09-03 10:41:04

标签: python string dictionary

如何以更高效的python友好方式执行以下操作?

first_team= re.sub("Northern", "N", first_team)
first_team=re.sub("Western", "W", first_team)
first_team=re.sub("Southern", "S", first_team)
first_team=re.sub("Eastern", "E", first_team)

4 个答案:

答案 0 :(得分:4)

使用for循环:

for direction in ('Northern', 'Western', 'Southern', 'Eastern'):
    first_team = first_team.replace(direction, direction[0])

这里没有必要使用re.sub处理这样简单的替换:),str.replace完全没问题。

答案 1 :(得分:3)

我会使用.replace并执行:

opts = [ ("Northern", "N"), ("Western", "W"), ("Southern", "S"), ("Eastern", "E") ]

for opt in opts:
    first_team = first_team.replace(opt[0], opt[1])

答案 2 :(得分:1)

您的re.sub()可以使用lambda作为第二个参数重写为一行:

>>> import re
>>> s = "Northern Western Southern Eastern" 
>>> re.sub("(Northern|Western|Southern|Eastern)", lambda x: x.group(1)[0] , s)
'N W S E'

请注意,替换过于简单,无法通过正则表达式进行。

但是,例如,如果您想要替换northNorth等字符串,该怎么办:

>>> s = "Northern North north Western Southern Eastern" 
>>> re.sub("([Nn]orth(ern)?|[Ww]est(ern)?|[Ss]outh(ern)?|[Ee]ast(ern)?)", lambda x: x.group(1)[0].upper(), s)
'N N N W S E'

那就是你可能需要使用re.sub


此外,您可以将replace()reduce()

一起使用
>>> opts = {"Northern": "N", "Western": "W", "Southern": "S", "Eastern": "E"}
>>> reduce(lambda k, v: k.replace(*v), opts.iteritems(), s)
'N W S E'

这与在for循环中应用replace()基本相同,但是以函数式编程风格编写。

答案 3 :(得分:0)

我想向您展示我自己的解决方案。在第一个视图中,它可能很复杂,但在定义“基础”之后,应用程序非常简单

首先,我将映射定义为元组列表:

our_mapping = [("Northern", "N"),
           ("Western", "W"),
           ("Southern", "S"),
           ("Eastern", "E")]

现在出现了问题:我定义了一个工厂函数,递归地创建了一体化替换功能:

def replacer_factory(mapping):
    if len(mapping) < 1:
        return lambda x: x
    original, replacement = mapping[0]
    return lambda x: replacer_factory(mapping[1:])(x.replace(original, replacement))

现在我可以使用我的映射创建替换函数:

our_replacer = replacer_factory(our_mapping)

然后应用程序非常简单:

>>> in_ = "Northern Western Southern Eastern"
>>> out_ = our_replacer(in_)
>>> print in_
Northern Western Southern Eastern
>>> print out_
N W S E

我真的很喜欢我们不需要任何参数来调用our_replacer,所有的映射逻辑都隐藏在其中。现在可以轻松定义任意替换器并使用它们。

这里代码整体:

our_mapping = [("Northern", "N"),
           ("Western", "W"),
           ("Southern", "S"),
           ("Eastern", "E")]

def replacer_factory(mapping):
    if len(mapping) < 1:
        return lambda x: x
    original, replacement = mapping[0]
    return lambda x: replacer_factory(mapping[1:])(x.replace(original, replacement))

our_replacer = replacer_factory(our_mapping)

in_ = "Northern Western Southern Eastern"
out_ = our_replacer(in_)

print in_
print out_

我同意这可以被认为是“先进的” - 所以如果你是一个新手,“只是想让它工作”,坚持jabaldonedos回答。