[英]Replacing phrases in string without using built-in python functions?
我正在尝试编写 function 来用也存储在列表中的首字母缩写词替换我存储在列表中的短语。 尝试在没有大多数内置函数的情况下执行此操作。 到目前为止,这是我最好的尝试:
def replace_phrase(string):
result = ''
for i in range(len(string)):
counter = 0
for phrase in phrases_to_replace_list:
if len(phrase) < len(string[i:]):
pass
elif string[i:i + len(phrase)] == phrase:
pre = string[:i]
post = string[i + len(phrase):]
result += pre + replacement_phrases[counter] + post
counter += 1
return result
有一串"Oh my god I love you got to go"
和"OMG ILY GTG"
的output是我想要实现的,但代码输出的是"Oh my god I love you GTG"
。
但是,在您的帖子中, OMG
和ILY
和GTG
之间没有space
逻辑。
所以只是假设可能有三个字符组。
您可以尝试以下代码:
def replace_phrase(string):
result =''
flag=True
cnt=3
for c in string.strip():
if c==' ':
flag=True
continue
if flag==True:
cnt+=1
result=result+c.upper()
if cnt%3==0:
result=result+' '
flag=False
return result
print(replace_phrase('Oh my god I love you got to go'))
Output:
OMG ILY GTG
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.