1

我有一个这样的字符串:

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

我想将此行替换为

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

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

我只知道如果有small字符串,我必须用那个名字和短的替换第一个和最后一个单词

有人可以帮忙吗?

4

4 回答 4

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'
于 2013-05-07T14:04:33.807 回答
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'
于 2013-05-07T14:04:31.217 回答
0

您可以在python中使用字符串替换方法..

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.
于 2013-05-07T14:06:54.780 回答
0

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

line = "Student   =  Small   |1-2|   Student"
name = line.split('=',1)[0].strip()
line = line.replace(name,name+'Short')
print line
于 2013-05-07T14:09:24.017 回答