Search code examples
pythonsplitisnumeric

changing a word in a string?


I have this assignment:

Write a function smallnr(x) that takes a number x and if x is an integer between 0 and 6 it returns the name of the number, otherwise it simply returns x 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 function convertsmall(s) that takes as input a text s and returns the text s 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?


Solution

  • 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:

    1. Divide the string into a list of words using text.split() - When no argument is passed, split() divides the string using ' ' (space) as delimiter.
    2. smallnr(int(word)) if word.isdigit() else word - Calls smallnr() if word is a number, otherwise returns word unchanged.
    3. Since 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.
    4. The entire phrase is a list comprehension, which processes each word in text.split() to product a new list. We join the words in this list together separated by spaces, using ' '.join(list).

    Hope that makes it clear :)