麻烦从字符串转换为int python [英] Troubles converting from string to int python

查看:156
本文介绍了麻烦从字符串转换为int python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究这个编码难题,并且必须将字符串中的一些数字转换为整数才能使用它们。一个例子是

I'm working on this coding puzzle and have to covert some numbers in a string to integers to work with them. an example would be

('2 -5 7 8 10 -205')

我尝试做的是将数字添加到空字符串中,并在有空格时将它们转换为int。这是代码。

What I tried to do was add the numbers to an empty string and convert them to an int when there was a space. Here's the code.

n是数字字符串的长度
num是我添加数字的空字符串。原来num =

n is the length of the string of numbers num is the empty string I add the numbers to. Originally num=""

  while i<n:

    if temps[i]!=' ':
        num=num+temps[i]


    elif temps[i]==' ':
        print type(num)

        x=int(num)

问题是当它运行时我得到一个错误line with x = int(num)say

The problem is that when it runs I get an error for the line with x=int(num) saying

ValueError: invalid literal for int() with base 10: ''

当我打印num时,我只是以字符串格式获取数字,所以我不明白什么是错的。帮助将非常感激,如果您有任何问题或需要澄清,请询问。

when i print num I just get numbers in a string format, so I don't understand what's wrong. Help would be really appreciated, and if you have any questions or need clarification please ask.

谢谢

推荐答案

使用 str.split()在空格处拆分字符串,然后应用 int 到每个元素:

Use str.split() to split your string at spaces, then apply int to every element:

s = '2 -5 7 8 10 -205'
nums = [int(num) for num in s.split()]

这篇关于麻烦从字符串转换为int python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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