0

I have a list of street names

streetNames = ['WELSESTRAAT', 'HENDRIKLAAN', 'LOMMERWEG']

And another list with street abbreviations

streetAbbr = [['WEG', 'WG'], ['STRAAT', 'STR'],['LAAN', 'LN']]

I am trying to loop through street names and replace straat with str, weg with wg and so on but I am stuck in the replace part as there is no such method for only part of a word.

for name in streetNames:
    for abbr in streetAbbr:
        if str(abbr[0]) in str(name):
            name.replace('straat', abbr[1]) #doesn't work 
3
  • Please edit your question. Improving question format will help other user read you and helping you. Commented Feb 20, 2020 at 10:20
  • In the last line shoud it not be name.replace(abbr[0], abbr[1])? And you don't need the str() call. Commented Feb 20, 2020 at 10:26
  • If you change name.replace('straat', abbr[1]) by name.replace(abbr[0], abbr[1]), it works fine here. Commented Feb 20, 2020 at 12:14

3 Answers 3

2

The issue in your code is that your are replacing on the variable over which you are iterating, which has no effect on the original list. Instead reassign to the list by indexing it:

d = dict(streetAbbr)
# {'WEG': 'WG', 'STRAAT': 'STR', 'LAAN': 'LN'}

for k,v in d.items():
    for i, name in enumerate(streetNames):
        if k in name:
            streetNames[i] = name.replace(k, v)

print(streetNames)
# ['WELSESTR', 'HENDRIKLN', 'LOMMERWG']
Sign up to request clarification or add additional context in comments.

Comments

1
result = [name.replace(abbr[0], abbr[1]) for name in streetNames for abbr in streetAbbr if abbr[0] in name]    

Comments

1

The issue here is that replace() function finds a blank space in order to replace strings. Since there is only a single word in your array, it's not working.

@Yatu's answer is correct but in case you don't want to update the data structures in your code, you can use this use-case specific solution.

for name in streetNames:
    for abbr in streetAbbr:
        if abbr[0] in name:
            new_str = name.split(abbr[0])
            name = f"{new_str[0]}{abbr[1]}" 
            print(name)

This solution may not work if there are multiple occurrences of the same substring in the names because of the usage of split. But since there are no such examples provided in the question it was assumed that this should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.