该函数假设在这两种情况下输入都是可以接受的(即)当对 str 执行 int 时假设 str 包含一个实际的 int,反之亦然总是有效
该函数也不得使用易于使用的 Python 内置函数,例如 int() 或 str()。只能使用基本编码以及 def 标头,例如(for i in rang() 和条件等等。)请帮助。:)
def str2int(s):
i = 0
chr2digit = {`j`:j for j in (0,1,2,3,4,5,6,7,8,9)}
for c in s:
i = i*10 + chr2digit[c]
return i
def int2str(i): # rather easy in Python2
return `i`
def int2str(i): # works in Python2 and Python3
return "%s"%i
它可能很难看,但它确实有效。看这个功能:
>>> def strint(val):
digits = '0123456789'
try:
# Trying to treat it as a string-to-int conversion
result = 0
for l in val:
result = result * 10 + digits.index(l)
except (TypeError,):
# There was a type error - we have int instead of string
result = ''
while val:
digit = val % 10
result = digits[digit] + result
val = val // 10
else:
if not val and not result:
result = '0'
return result
>>> strint('123')
123
>>> strint(123)
'123'
>>> strint('0')
0
>>> strint(0)
'0'
这只是为了int
更换,并不能处理所有事情,但这是家庭作业,所以我会让你做剩下的。如果您使用ord
.
def myint(s):
x = 0
for ch in s:
if ch == '0': x = x * 10 + 0
if ch == '1': x = x * 10 + 1
if ch == '2': x = x * 10 + 2
if ch == '3': x = x * 10 + 3
if ch == '4': x = x * 10 + 4
if ch == '5': x = x * 10 + 5
if ch == '6': x = x * 10 + 6
if ch == '7': x = x * 10 + 7
if ch == '8': x = x * 10 + 8
if ch == '9': x = x * 10 + 9
return x
这是您可以考虑的一种方法:
x = "1"
print type(x)
<type 'str'>
import string
if x in string.digits:
# Now you know that x is a number
print x
你也可以对string.ascii_letters做同样的事情。不是一个完整的答案,但应该指出你正确的方向。