I have a address list as :
addr = ['100 NORTH MAIN ROAD',
'100 BROAD ROAD APT.',
'SAROJINI DEVI ROAD',
'BROAD AVENUE ROAD']
I need to do my replacement work in a following function:
def subst(pattern, replace_str, string):
by defining a pattern outside of this function and passing it as an argument to subst.
I need an output like:
addr = ['100 NORTH MAIN RD',
'100 BROAD RD APT.',
'SAROJINI DEVI RD ',
'BROAD AVENUE RD']
where all 'ROAD' strings are replaced with 'RD'
def subst(pattern, replace_str, string):
#susbstitute pattern and return it
new=[]
for x in string:
new.insert((re.sub(r'^(ROAD)','RD',x)),x)
return new
def main():
addr = ['100 NORTH MAIN ROAD',
'100 BROAD ROAD APT.',
'SAROJINI DEVI ROAD',
'BROAD AVENUE ROAD']
#Create pattern Implementation here
pattern=r'^(ROAD)'
print (pattern)
#Use subst function to replace 'ROAD' to 'RD.',Store as new_address
new_address=subst(pattern,'RD',addr)
return new_address
I have done this and getting below error
Traceback (most recent call last):
File "python", line 23, in File "python", line 20, in main File "python", line 7, in subst
TypeError: 'str' object cannot be interpreted as an integer
5条答案
按热度按时间lrpiutwd1#
No need for regex, just use
replace
:If you only want to replace the
ROAD
as a word, no in the middle, use:9nvpjoqh2#
Using
re
Output:
q43xntqr3#
uz75evzq4#
I got the answer,
passing this a parameter to
we can get the op :)
cgyqldqp5#
TRy this
!/bin/python3
import sys import os import io import re
Complete the function below.
def subst(pattern, replace_str, string): #susbstitute pattern and return it new_address=[pattern.sub(replace_str,st) for st in string] return new_address def main(): addr = ['100 NORTH MAIN ROAD', '100 BROAD ROAD APT.', 'SAROJINI DEVI ROAD', 'BROAD AVENUE ROAD']
'''For testing the code, no input is required'''
if name == "main": main()
def bind(func): func.data = 9 return func
@bind def add(x, y): return x + y
print(add(3, 10)) print(add.data)