我想更改我的字符串类型。 我想让它们为整数以比较哪个更大。
#numbers="4, 5, 29, 54, 4 ,0 ,-214, 542, -64, 1 ,-3, 6, -6"
#ns=numbers.split()
#nsi=[]
#for i in range(len(ns)):
# ns[i]=int(ns[i])
# nsi.append(ns[i])
# enter code here
#print(nsi)
Thank you
i am getting error like this
# ns[i]=int(ns[i])
#ValueError: invalid literal for int() with base 10: '4,'
The issue is that
split()
uses a whitespace as default split character. So there is still the comma left. You are able to specify the separator for the function withsplit(', ')
.See this example on how split is used.
您可以在split()中使用其他分隔符。请注意,尽管要正确准备字符串(始终以“,”而不是“,”分隔)
你可以做
要么
这会将所有数字转换为int。
当您分割字符串时,它会被空格分割...因此每个数字仍然带有逗号。
固定:
你犯了一个错误。
更改此行
入这个