相关文章推荐
不羁的高山  ·  java ...·  5 月前    · 
憨厚的黄瓜  ·  python - Why ...·  1 年前    · 
#convert to a string listToStr = ' '.join([str(elem) for elem in my_list]) print(listToStr)

但这返回了错误。ValueError: invalid literal for int() with base 10: '54.123'.

有谁知道解决这个问题的办法吗?

1 个评论
AMC
那么,你对这个错误怎么看?
python
math
newlander007
newlander007
发布于 2019-11-24
3 个回答
narancs
narancs
发布于 2019-11-24
已采纳
0 人赞同

你可以尝试将当前行转换为一个浮点数。如果该行不包含合法的浮点数,它会返回一个ValueError异常,你可以捕捉并直接传递。如果没有抛出异常,只需在点处分割该行,将两部分连接起来,转换为int并添加到数组中。

my_list = []
with open('file.txt') as f:
    lines = f.readlines()
    for line in lines:
            tmp = float(line)
            num = int(''.join(line.split(".")))
            my_list.append(num)
        except ValueError:
#convert to a string
listToStr = ' '.join([str(elem) for elem in my_list])
print(listToStr)
    
lbragile
lbragile
发布于 2019-11-24
0 人赞同

你可以使用 isdigit() 函数检查给定的行是否是一个代表数字的字符串。

据我所知,你只需要检查是否有一个数字,因为 isdigit() 只对整数有效(浮点数包含".",这不是一个数字,它返回False)。

def numCheck(string):
  # Checks if the input string contains numbers
  return any(i.isdigit() for i in string)
string = '54.123'
print(numCheck(string)) # True
string = 'hello'
print(numCheck(string)) # False

注意:如果你的数据包含像123ab56这样的东西,那么这对你就没有好处。

To convert 54.123 to 54123 you could use the replace(old, new) function.

string = 54.123
new_string = string.replace('.', '') # replace . with nothing
print(new_string) # 54123
    
谢谢你的评论!我将研究一下!
Muhammad Yusuf
Muhammad Yusuf
发布于 2019-11-24
0 人赞同

这可能会有帮助,我现在从文件中得到了数字,我想你是想用分割来代替剥离。

import re
exp = re.compile(r'[0-9]')
my_list = []
with open('file.txt') as f:
    lines = f.readlines()
    for line in lines:
        for numbers in line.split():
            if re.match(exp, numbers):
                my_list.append(numbers)