继续在这个简单的 Python 函数中似乎不起作用
Continue doesn't seem to work in this simple Python function
该函数应该将字符串作为输入,return(如果字符串的所有成员都是数字)和该字符串的整数版本。此示例中提供的字符串是一个 3 位数字。该函数的 for 循环似乎只有 return 第一个数字,因此继续可能无法按预期工作。
e = '484'
def resolving(e):
for i, o in enumerate(e):
if o in "0123456789":
s = []
s.append(o)
i += 1
continue
elif o not in "0123456789":
print(type(e))
return e
k = str(s)
y = k.replace("'","").replace("[","").replace("]","").replace(",","").replace(" ","")
p = int(y)
print(type(p))
return p
print(resolving(e))
你有 return
在那里,所以当你第一次点击 non-numeric 字符时,你将 return 该字符并退出。如所写,continue 不会执行任何操作,因为以下 elif
不会被任何将您发送到 if 语句的第一个分支的字符击中。
因为你在循环中创建列表。只是让它在循环之外。此外,使用 str.join
代替 str(s)
使列表的字符串表示形式,因为它将列表的所有元素连接成一个字符串。也不需要 continue 语句。因为 elif 不会 运行 如果 if 为真。
for i, o in enumerate(e):
s = []
if o in "0123456789":
s.append(o)
else:
print(type(e))
return e
k = ''.join(s)
p = int(y)
return p
冒着完全错失要点的风险,整个功能可能只是:
def resolve(e):
"""If e is convertible to an int, return its int value;
otherwise print its type and return the original value."""
try:
return int(e)
except ValueError:
print(type(e))
return e
如果你只把一个字符串的整数作为它的整数版本,你可以使用isnumeric()
检查:
def resolve(e)
return int(''.join([i for i in e if i.isnumeric()]))
该函数应该将字符串作为输入,return(如果字符串的所有成员都是数字)和该字符串的整数版本。此示例中提供的字符串是一个 3 位数字。该函数的 for 循环似乎只有 return 第一个数字,因此继续可能无法按预期工作。
e = '484'
def resolving(e):
for i, o in enumerate(e):
if o in "0123456789":
s = []
s.append(o)
i += 1
continue
elif o not in "0123456789":
print(type(e))
return e
k = str(s)
y = k.replace("'","").replace("[","").replace("]","").replace(",","").replace(" ","")
p = int(y)
print(type(p))
return p
print(resolving(e))
你有 return
在那里,所以当你第一次点击 non-numeric 字符时,你将 return 该字符并退出。如所写,continue 不会执行任何操作,因为以下 elif
不会被任何将您发送到 if 语句的第一个分支的字符击中。
因为你在循环中创建列表。只是让它在循环之外。此外,使用 str.join
代替 str(s)
使列表的字符串表示形式,因为它将列表的所有元素连接成一个字符串。也不需要 continue 语句。因为 elif 不会 运行 如果 if 为真。
for i, o in enumerate(e):
s = []
if o in "0123456789":
s.append(o)
else:
print(type(e))
return e
k = ''.join(s)
p = int(y)
return p
冒着完全错失要点的风险,整个功能可能只是:
def resolve(e):
"""If e is convertible to an int, return its int value;
otherwise print its type and return the original value."""
try:
return int(e)
except ValueError:
print(type(e))
return e
如果你只把一个字符串的整数作为它的整数版本,你可以使用isnumeric()
检查:
def resolve(e)
return int(''.join([i for i in e if i.isnumeric()]))