将1234分成('1','2','3','4') [英] split 1234 into ('1', '2', '3', '4')

查看:116
本文介绍了将1234分成('1','2','3','4')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我想知道是否有一种简单的方法可以将1234分成一串(''1'','''',''3' ',''4'')。


另外,有没有办法测试字符串(或列表)的元素是否为整数。例如,如果我有一个列表a = [''1'','''',''3'',''4''],则元素都是整数,函数需要返回True。 br />

然而,如果列表是['''',''2',''3'',''x''],我怎么能区分'' x''不是整数,因此函数返回False。


到目前为止,我使用了for循环:

for i in a:

如果int(i)是type(int):

返回True

如果int(i)不是type(int):

返回False


但这根本不起作用。


感谢您的帮助:)

Hi,

I was wondering if there is a simple way to split 1234 into a string of (''1'', ''2'', ''3'', ''4'').

Also, is there a way to test whether an element of a string (or list) is an integer. For instance, if i had a list a = [''1'', ''2'', ''3'', ''4''], the elements are all integers, the function needs to return True.

However, if the list was [''1'', ''2'', ''3'', ''x''], how would i distinguish that ''x'' is not an integer and therefore the function would return False.

So far i have used a for loop:
for i in a:
if int(i) is type(int):
return True
if int(i) is not type(int):
return False

but this isn''t working at all.

Thanks for your help :)

推荐答案



str()函数接受一个整数参数并返回一个字符串。您还可以使用list()和tuple()函数将字符串转换为列表和元组。你的循环有两个问题。当找到一个数字时,它甚至在检查其他字符串之前返回true。您需要创建一个循环,一旦找到非数字字符串就退出,并且只有在它完全通过列表并且没有问题时才返回true。其次,如果找到一个不转换为整数的字符串,int(i)将使用ValueError使程序崩溃。使用它对您有利。创建一个try-except块来检测值是否为int。

希望这会有所帮助。
Hi,
The str() function takes an integer argument and returns a string. You can also use the list() and tuple() functions to convert strings to lists and tuples. Your loop has two problems. When it finds a number, it returns true before even checking the other strings. You need to make a loop that quits as soon as it finds a non-number string, and only return true if it goes all the way through the list with no problems. Secondly, int(i) will crash your program with a ValueError if it finds a string that does not convert to an integer. Use this to your advantage. Make a try-except block to detect whether the value is an int or not.
Hope this helps.


我也建议你改变你的测试:
Also i would suggest that you''d change your test to:
展开 | 选择 < span class =codeDivider> | Wrap | 行号


你可以这样做。
You can do this.
展开 | 选择 | Wrap | 行号


这篇关于将1234分成('1','2','3','4')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆