在Python中查找并替换字符串

时间:2013-05-07 14:03:19

标签: python

我有一个这样的字符串:

 line = "Student   =  Small   |1-2|   Student"

我想将此行替换为

 line = "StudentShort  =  Small  |1-2|    StudentShort"

问题是我不知道第一个和最后一个单词是Student还是其他任何字符串。我的意思是它可以是MenWomenTeacher任何内容。

我只知道如果字符串中有small,我必须用该名称替换第一个和最后一个单词并缩短

有人能帮忙吗?

4 个答案:

答案 0 :(得分:2)

你想为字符串的第一个和最后一个字添加“Short”...我的建议是拆分然后使用索引然后加入!

In [202]: line = "Teacher   =  Small   |1-2|   Student"

In [203]: line = line.split()

In [204]: line[0] += "Short"

In [205]: line[-1] += "Short"

In [206]: line = "  ".join(line)

In [207]: line
Out[207]: 'TeacherShort  =  Small  |1-2|  StudentShort'

我认为在函数中使用它会很有用:

def customize_string(string,add_on):
    if "small" in string:
        line = string.split()
        line[0] += add_on
        line[-1] += add_on
        return "  ".join(line)
    else:
        return string

这里用它来证明它有效!

In [219]: customize_string(line,"Short")
Out[219]: 'TeacherShort  =  Small  |1-2|  StudentShort'

答案 1 :(得分:1)

使用regex

这样的事情
>>> line = "Student   =  Small   |1-2|   Student"
>>> if re.search(r"\bSmall\b",line):
    print re.sub("^(\w+)|(\w+)$",lambda x:x.group()+"Short",line)
'StudentShort   =  Small   |1-2|   StudentShort'

>>> line = "Men   =  Small   |1-2|   Men"
>>> if re.search(r"\bSmall\b",line):
    print re.sub("^(\w+)|(\w+)$",lambda x:x.group()+"Short",line)
'MenShort   =  Small   |1-2|   MenShort'

上述代码的改进版本(由@ thg435建议):

def solve(strs, match, word):
    if re.search(r"\b{0}\b".format(match), strs):
         return re.sub(r"(^\w+|\w+$)","\g<0>{0}".format(word), strs)

>>> solve("Men   =  Small   |1-2|   Men", "Small", "Short")
'MenShort   =  Small   |1-2|   MenShort'
>>> solve("Student   =  Small   |1-2|   Student", "Small", "Short")
'StudentShort   =  Small   |1-2|   StudentShort'

答案 2 :(得分:0)

您可以在python中使用String替换方法..

http://docs.python.org/2/library/string.html#string.replace

    string.replace(s, old, new[, maxreplace])
    Return a copy of string s with all occurrences of substring
    old replaced by new. If the optional argument maxreplace is 
    given, the first maxreplace occurrences are replaced.

答案 3 :(得分:0)

通过拆分字符串,根据等号选择“学生”部分。然后用line.replace替换它。

line = "Student   =  Small   |1-2|   Student"
name = line.split('=',1)[0].strip()
line = line.replace(name,name+'Short')
print line
相关问题