cookie1986
cookie1986

Reputation: 895

Transforming integers in a string to words in a list comprehension

I have a string that contains integers and I am trying to work out how to transform them into words (i.e. 100 into one hundred). I am using the inflect package with success with individual cases, however I am struggling to find the correct solution that enables me to keep the sentence as-is, aside from the integer transformation.

This is what I have at present:

mysent = ['this','is','1','of','my','sentences']

and this is what i want to end up with:

mysent = ['this','is','one','of','my','sentences']

So far I have tried the following, which is removing all words except the integer.

import inflect
p = inflect.engine()

mysent = [p.number_to_words(token) for token in mysent if token.isdigit() is True]

I have also tried the below which I thought might solve the problem, but produces a syntax error:

mysent = [p.number_to_words(token) for token in mysent if token.isdigit() is True else token for token in mysent]

Upvotes: 2

Views: 59

Answers (2)

kaya3
kaya3

Reputation: 51093

When you write if after for in a list comprehension, you are filtering the list by excluding those elements for which the condition is false. This means you exclude the non-numeric words, which isn't what you want.

Instead, you should write p.number_to_words(token) if token.isdigit() else token to include either the conversion, or the original token, into the resulting list, depending on the condition. The full comprehension looks like this:

mysent = [p.number_to_words(token) if token.isdigit() else token for token in mysent]

By the way, assuming token.isdigit() returns either True or False, it is redundant to write is True.

Upvotes: 3

Dani Mesejo
Dani Mesejo

Reputation: 61910

You could use Python's ternary operator:

result = [p.number_to_words(token) if token.isdigit() else token for token in mysent]

print(result)

Output

['this', 'is', 'one', 'of', 'my', 'sentences']

Upvotes: 3

Related Questions