Assume that a poem is given. Write the regular expressions for the following:
If the pattern has characters 'ai' or 'hi', replace the next three characters with *\*.
poem ='''
If I can stop one heart from breaking,
I shall not live in vain;
If I can ease one life the aching,
Or cool one pain,
Or help one fainting robin
Unto his nest again,
I shall not live in vain.'''
What have you tried? We're not big on writing code for people here, but we would be happy to help you fix your code when you run into problems. When you do run into problems, please post your code in
Python tags, and clearly explain the problem you are having, including the full text of any errors.
See, I was trying this code:
c = poem
a = c.split(" ")
for i in range(0,len(a)):
laura = 0
for j in range(0,len(a[i])):
if len(a[i])>6:
laura = 0
elif a[i][j] == "\n":
laura = 1
if len(a[i])>=6 and laura == 0:
list_=list(a[i])
for j in range(0,len(list_)):
if list_[j] =="a" and list_[j+1] =="i":
list_[j+2] = "*"
list_[j+3] = "\\"
list_[j+4] = "*"
temp=""
for j in list_:
temp+=j
a[i] = temp
list__=list(a[i])
for j in range(0,len(list__)):
if list__[j] =="h" and list__[j+1] =="i":
list__[j+2] = "*"
list__[j+3] = "\\"
list__[j+4] = "*"
temp1=""
for j in list__:
temp1+=j
a[i] = temp1
b =""
for i in range(0,len(a)):
b+=a[i] +" "
print(b)
I am getting this Output:
Output:
If I can stop one heart from breaking,
I shall not live in vai*\*If I can ease one life the achi*\*
Or cool one pai*\*Or help one fai*\*ng robin
Unto his nest agai*\*I shall not live in vain.
But the real output is
Output:
If I can stop one heart from breaking,
I shall not live in vain;
If I can ease one life the achi*\*
Or cool one pain,
Or help one fai*\*ng robin
Unto hi*\*est again,
I shall not live in vain.
Your assignment says to use a regular expression, and you have failed to do that. You should read up on the
re module, it will make the task so much simpler.
Without regex (kiss):
poem.replace('ai', '*/*').replace('hi', '*/*')
A regex, which will detect ai and hi:
r'ai|hi'
You can use
re.sub
for replacement.
To construct or check a regex, you should visit this site:
https://regex101.com/