Convert an amount to Indian Notation in Python

前端 未结 5 701
离开以前
离开以前 2021-01-02 03:40

Problem: I need to convert an amount to Indian currency format

My code: I have the following Python implementation:

5条回答
  •  悲&欢浪女
    2021-01-02 04:29

    Couldn't make the other two solutions work for me, so I made something a little more low-tech:

    def format_as_indian(input):
        input_list = list(str(input))
        if len(input_list) <= 1:
            formatted_input = input
        else:
            first_number = input_list.pop(0)
            last_number = input_list.pop()
            formatted_input = first_number + (
                (''.join(l + ',' * (n % 2 == 1) for n, l in enumerate(reversed(input_list)))[::-1] + last_number)
            )
    
            if len(input_list) % 2 == 0:
                formatted_input.lstrip(',')
    
        return formatted_input
    

    This doesn't work with decimals. If you need that, I would suggest saving the decimal portion into another variable and adding it back in at the end.

提交回复
热议问题