Python不接受某些数字输入

pos*_*nim 3 python

使用此代码,我想要做的就是在偶数之间插入一个短划线和偶数之间的星号.每次输入都无法正常工作.它适用于例如46879,但是返回None为468799,或者不在4和6之间插入*4546793.为什么这样做?谢谢

def DashInsertII(num): 

 num_str = str(num)

 flag_even=False
 flag_odd=False

 new_str = ''
 for i in num_str:
  n = int(i)
  if n % 2 == 0:
   flag_even = True
  else:
   flag_even = False
  if n % 2 != 0:
   flag_odd = True
  else:
   flag_odd = False
  new_str = new_str + i
  ind = num_str.index(i)

  if ind < len(num_str) - 1:
   m = int(num_str[ind+1])
   if flag_even:
    if m % 2 == 0:
      new_str = new_str + '*'
   else:                 
    if m % 2 != 0:
      new_str = new_str + '-'                     
 else:
  return new_str  
 print DashInsertII(raw_input()) 
Run Code Online (Sandbox Code Playgroud)

Rev*_*ght 5

你的函数定义是我在一段时间内看到的最过度构建的函数之一; 以下应该做你想做的事,没有复杂性.

def DashInsertII(num):
  num_str = str(num)

  new_str = ''
  for i in num_str:
    n = int(i)
    if n % 2 == 0:
      new_str += i + '*'
    else:
      new_str += i + '-'
  return new_str
print DashInsertII(raw_input()) 
Run Code Online (Sandbox Code Playgroud)

编辑:我只是重新阅读这个问题,看到我误解了你想要的东西,即插入-两个奇数和两个偶数*之间的数字.为此,我能提出的最佳解决方案是使用正则表达式.

第二次编辑:根据alvits的要求,我在这里包括对正则表达式的解释.

import re

def DashInsertII(num):
  num_str = str(num)

  # r'([02468])([02468])' performs capturing matches on two even numbers
  #    that are next to each other
  # r'\1*\2' is a string consisting of the first match ([02468]) followed
  #    by an asterisk ('*') and the second match ([02468])
  # example input: 48 [A representation of what happens inside re.sub()]
  #    r'([02468])([02468])' <- 48 = r'( \1 : 4 )( \2 : 8 )'
  #    r'\1*\2' <- {\1 : 4, \2 : 8} = r'4*8'
  num_str = re.sub(r'([02468])([02468])',r'\1*\2',num_str)
  # This statement is much like the previous, but it matches on odd pairs
  #    of numbers
  num_str = re.sub(r'([13579])([13579])',r'\1-\2',num_str)

  return num_str

print DashInsertII(raw_input())
Run Code Online (Sandbox Code Playgroud)

如果这仍然不是您真正想要的,请对此发表评论告诉我.