我正在寻找一些帮助,从python脚本中重新格式化一行文本,以便我可以用其他字符替换某些字符,或者用特定字符替换空格。为清楚起见,我尝试重新格式化的文本被分配给变量。
我搜索过这个功能,但我还没有看到如何做到这一点!
答案 0 :(得分:-1)
我试图为您编写一个完整的功能以满足您的目的:
def posSubStringReplaceRecursively(string1, search, replace, pos, is_First):
global string2
if is_First:
string2 = list(copy.deepcopy(string1))
is_First = False
index = str.rfind(string1, search)
if index != -1:
string1 = string1[:(index+len(search)-1)]
pos.append(index)
return posSubStringReplaceRecursively(string1, search, replace, pos, is_First)
else:
pos = pos
for i in xrange(len(pos)):
string2[pos[i]:pos[i]+len(search)] = replace
string2 = " ".join(string2)
return string2
调用该函数:
string1 = raw_input("Enter string:\n")
search = raw_input("Enter word to find:\n")
replace = raw_input("Enter word to replace:\n")
print posSubStringReplaceRecursively(string1, search, replace, [], True)