如何在python中将字符串列表中的int转换为int?

时间:2015-04-28 05:37:56

标签: python

例如,我有一个字符串列表:

lst = ["hello","ASKDJ","1","4","xcvs"]

如何将字符串列表中的整数转换为整数?

4 个答案:

答案 0 :(得分:3)

有条件地将元素转换为整数,包括所有字符串字符都是数字。如果字符串的所有元素都是数字,则字符串方法str.isdigit返回true。

>>> [int(elem ) if elem.isdigit() else elem for elem in lst]
['hello', 'ASKDJ', 1, 4, 'xcvs']

答案 1 :(得分:2)

使用string.isdigit()方法和list comprehensions

  

str.isdigit()

     

如果字符串中的所有字符都是数字,则返回true   并且至少有一个角色,否则为假。

def to_ints_if_possible(seq):
    return [int(s) if s.isdigit() else s for s in seq]
lst = ["hello","ASKDJ","1","4","xcvs"]
converted = to_ints_if_possible(lst)

答案 2 :(得分:1)

您在该列表中没有任何整数,只是字符串。您可以使用函数int将某些字符串转换为整数。

lst = ["hello","ASKDJ","1","4","xcvs"]

for index, item in enumerate(lst):
    try:
        foo = int(item)
        lst[index] = foo
    except ValueError, e:
        print("Item " + item + " cannot be turned into a number!")
        print(e)
        continue

您将获得以下输出:

>>> 
Item hello cannot be turned into a number!
invalid literal for int() with base 10: 'hello'
Item ASKDJ cannot be turned into a number!
invalid literal for int() with base 10: 'ASKDJ'
Item xcvs cannot be turned into a number!
invalid literal for int() with base 10: 'xcvs'

现在尝试打印列表:

>>> lst
['hello', 'ASKDJ', 1, 4, 'xcvs']

答案 3 :(得分:0)

def convert(L):
    for i, elem in enumerate(L):
        if not elem.isdigit():
            continue
        L[i] = int(elem)

In [12]: L = ["hello","ASKDJ","1","4","xcvs"]

In [13]: convert(L)

In [14]: L
Out[14]: ['hello', 'ASKDJ', 1, 4, 'xcvs']