Skip to main content
 首页 » 编程设计

python之将字符串转换为 int,反之亦然

2025年05月04日19sxdcgaq8080

我需要在进行一些处理后将字符串转换为 int 并返回。字符串必须像下面这样:

45 - 四十五
99 - 九十九

我到处搜索提示,但找不到任何提示。我知道明显的 switch-case 逻辑,但我很好奇是否有更智能的方法来使用更少的代码行。

请您参考如下方法:

使用 num2words,参见( https://www.geeksforgeeks.org/python-number-to-words-using-num2words/ )

  from num2words import num2words 
  def num2word(num): 
     """ 
      convert numbers in a string to their word representation 
     """   
     try: 
         return num2words(num, lang='en_IN') 
     except: 
         return num