我正在创建一个带字符串的函数并替换" put"并且"得到"用" xput()"和" xget()"。我知道它不是最有效的,但我想从开始工作开始。它目前取代了广告放置括号的字样,但它在每个换行符上都添加括号,我不明白为什么。有人能帮助我吗?
代码:
import re
def replaceFunctions(string):
split=re.split('(\n)', string)
for i in range (0,len(split)):
split[i] = re.split('(")',split[i])
split = [item for sublist in split for item in sublist]
for i in range (0,len(split)):
split[i]=re.split('( )', split[i])
split = [item for sublist in split for item in sublist]
for i in range (0,len(split)):
split[i]=re.split('(\t)', split[i])
split = [item for sublist in split for item in sublist]
split.append("\n")
for i in range (0,len(split)):
if split[i] == "put":
split[i] = "xput ("
for o in range (i,len(split)):
if split[o] == "\n":
split[o] = ")\n"
break
else:
if split[i] == "get":
split[i] = "xget ("
for o in range (i,len(split)):
if split[o] == "\n":
split[o] = ")\n"
break
string = ""
for i in range (0,len(split)):
string += split[i]
return string
print "get (put)"
print replaceFunctions("get (put)")
print "put \"put this\"\nput put (get)\n\n\nput\n"
print replaceFunctions("put \"put this\"\nput put (get)\n\n\nput")
输出:
get (put)
xget ( (put))
put "put this"
put put (get)
put
xput ( "xput ( this")
xput ( xput ( (get))
)
)
xput ()
期望的输出:
get (put)
xget ( (put))
put "put this"
put put (get)
put
xput ( "xput ( this")
xput ( xput ( (get))
xput ()
提前致谢!
答案 0 :(得分:3)
这会有用吗?
>>> txt = 'this is a text with get, some more get and even a put or two put'
>>> txt.replace('get', 'xget()').replace('put', 'xput()')
'this is a text with xget(), some more xget() and even a xput() or two xput()'
答案 1 :(得分:0)
不像@SciGuyMcQ那么紧凑,但更多"可扩展":
txt = 'this is a text with get, some more get and even a put or two put'
table = {'get': 'get()',
'put': 'xput()'}
result = txt[:]
for key in table:
result = result.replace(key, table[key])
输出:
>>> result
'This is a text with get(), more get() and also xput() and xput() again.'