I have this assignment:
Write a function
smallnr(x)
that takes a numberx
and ifx
is an integer between0
and6
it returns the name of the number, otherwise it simply returnsx
as a string.
I did the following:
def smallnr(x):
if x>6:
return str(x)
else:
lst=['zero','one','two','three','four','five','six']
return (lst[x])
and that works, but now I have to do this:
Using the function
smallnr
from part a, write a functionconvertsmall(s)
that takes as input a texts
and returns the texts
with small numbers (integers between 0 and 6) converted to their names. For example,convertsmall('I have 5 brothers and 2 sisters, 7 siblings altogether.') 'I have five brothers and two sisters, 7 siblings altogether.'
I know I need to use split()
and isnumeric()
somehow, but I can't figure out how to put it all together and change just the numbers within the string.
Any advice?
Here's the easiest way to do this (in my opinion):
def convertsmall(text):
return ' '.join(smallnr(int(word)) if word.isdigit() else word for word in text.split())
Output:
>>> convertsmall('I have 5 brothers and 2 sisters, 7 siblings altogether.')
'I have five brothers and two sisters, 7 siblings altogether.'
To understand this, let's go backwards:
list
of words using text.split()
- When no argument is passed, split() divides the string using ' '
(space) as delimiter.smallnr(int(word)) if word.isdigit() else word
- Calls smallnr()
if word
is a number, otherwise returns word
unchanged.word
is a string, we need to convert it into an integer using int(word)
before passing it to your function, which assumes x
to be an integer.word
in text.split()
to product a new list. We join the word
s in this list together separated by spaces, using ' '.join(list).Hope that makes it clear :)