在Python中查找并替换字符串
我有这样一个字符串:在Python中查找并替换字符串,python,Python,我有这样一个字符串: line = "Student = Small |1-2| Student" 我想把这条线换成 line = "StudentShort = Small |1-2| StudentShort" 问题是我不知道第一个和最后一个单词是Student还是字符串中的任何其他单词。我的意思是它可以是男人,女人,老师任何东西 我只知道,如果字符串中有small,我就必须用这个名字和short替换第一个和最后一个单词 有人能帮忙吗?使用regex类似的东
line = "Student = Small |1-2| Student"
我想把这条线换成
line = "StudentShort = Small |1-2| StudentShort"
问题是我不知道第一个和最后一个单词是
Student
还是字符串中的任何其他单词。我的意思是它可以是男人
,女人
,老师
任何东西
我只知道,如果字符串中有small
,我就必须用这个名字和short替换第一个和最后一个单词
有人能帮忙吗?使用
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):
如果重新搜索(r“\b{0}\b.”格式(匹配),strs):
返回re.sub(r“(^\w+\w+$)”,“\g{0}”.format(word),strs)
>>>解决(“男人=小的| 1-2 |男人”,“小的”,“短的”)
“门肖特=小| 1-2 |门肖特”
>>>求解(“学生=小| 1-2 |学生”,“小”,“短”)
“StudentShort=Small | 1-2 | StudentShort”
您想在字符串的第一个和最后一个单词中添加“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'
可以在python中使用字符串替换方法
这将通过拆分字符串,基于等号选择“学生”部分。然后使用line.replace替换它
line = "Student = Small |1-2| Student"
name = line.split('=',1)[0].strip()
line = line.replace(name,name+'Short')
print line
问题是我不知道stringJust\1Short
中的第一个和最后一个单词是什么,而不是lambda。@thg435我在使用lambda
之前尝试过,但它返回了。\x01Short
并且在原始字符串中引发了错误。@AshwiniChaudhary:有趣。您可能希望将expr更改为(^\w+\w+$)
,或者使用\g
来代替组0。您忘记回答整个问题了!如果字符串包含“small”,他只需要添加“Short”。问题是我不知道字符串中的第一个和最后一个单词是什么。你的问题不清楚,这满足了你的示例……那么你的意思是,你希望能够替换一个实例,而不知道它是什么?是的,问题是我不知道我的第一个和最后一个字在字符串中是什么,可以是老师,也可以是男人或女人,所以你的问题在学生中并不都是这样,而是第一个和最后一个字?字符串的格式是所有内容都用两个空格分隔吗?str.split
不会保留字符串中不规则的空格。问题是我不知道我在字符串中的第一个和最后一个单词是什么。你可以通过拆分字符串并获得第一个和最后一个单词p.split()[0](给出第一个)splitListCount=len(line.split());last=line.split()[splitListCount-1];
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.
line = "Student = Small |1-2| Student"
name = line.split('=',1)[0].strip()
line = line.replace(name,name+'Short')
print line