converting individual digits to string

后端 未结 4 873
感动是毒
感动是毒 2021-01-28 11:38

I think i\'m very close but i cant seem to fix my issues. I need a function that takes a 10-digit input from user (me) and sets each letter to is numeric value.

Example:

4条回答
  •  囚心锁ツ
    2021-01-28 12:14

    You can create a formula to ascertain the correct number to add depending on the letter:

    math.ceil((index(char)+1)/3)
    

    Use a list and depending on which character it is, append a number to the list. At the end, return the list, but joined so that it is a string:

    def numerify(inp):
            from math import ceil as _ceil
            from string import lowercase as _lowercase
            chars = []
            for char in inp:
                    if char.isalpha():
                            num = _ceil((_lowercase.index(char)+1)/float(3))
                            chars.append(str(int(num+1)))
                    else:
                            chars.append(char)
            return ''.join(chars)
    

    >>> from numerify import numerify
    >>> numerify('1')
    '1'
    >>> numerify('941-019-abcd')
    '941-019-2223'
    >>>
    

提交回复
热议问题