user3827326
user3827326

Reputation:

Shorten method chaining in Python variable

I have the following code:

numbers = foo.replace('one', '1').replace('two', '2').replace('three', '3')

This is part of a bigger project that takes a list, changes the words to numbers and writes them into one column in a CSV file. My question is if there's a way to shorten the method chaining above. Would a loop be appropriate here?

Upvotes: 0

Views: 170

Answers (1)

John La Rooy
John La Rooy

Reputation: 304473

You could use something like this

replacements = [('one', '1'), ('two', '2'), ('three', '3'), ...]
numbers = foo
for item in replacements:
    numbers = numbers.replace(*item)

It makes a lot of temporary strings however (as does your chained replace method)

You may also find you have undesired replacements to words like "phone"

If possible you should split your foo into a list of words. Then look up the replacements from a dict

replace_dict = dict(one=1, two=2, three=3)
foo_list = foo.split(' ')
foo = ' '.join(replace_dict.get(k, k) for k in foo_list)

Upvotes: 5

Related Questions