如何拆分字符串并转换为整数

时间:2016-05-29 21:59:46

标签: python string

numbers = "51-52"
for st in numbers:
    part = st.split("-")
    print(part)

到目前为止,这是我的代码。

我的成绩:['5'] ['1'] ['',''] ['5'] ['2']

预期:[ '51'] [ '52']

3 个答案:

答案 0 :(得分:3)

因为它应该只是:

numbers = "51-52"
print numbers.split("-")

答案 1 :(得分:2)

for st in numbers将遍历字符串中的每个字符,因此您最终会在结果集中将每个字符分开。把它留下来,只需

numbers = "51-52"
parts = numbers.split("-")
print(parts)

答案 2 :(得分:0)

numbers = "51-52"
part = [int(x) for x in numbers.split("-")]
print(part)