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

Help, I keep getting ValueError: Invalid literal for int () with base 10: '' when I try to extract an integer from a string!

from string import capwords
import sys,os
import re

def parseint(List):
    newlist = [i for i in List if isinstance(i, int)]
    return newlist
def getint(string):
    number = [int(x) for x in string.split("-")]
    return number

file=open('./Class 1/','r')

def get_num(x):
    return int(''.join(ele for ele in x if ele.isdigit()))

split = text.split(",")

split.sort(key = lambda k : k.lower())
for i in split:

print ('---------------------------------------')
for i in split:


for i in list1:
    ints = re.findall(r'\b\d+\b', i)

    #ints = getint(i)[0]
    for i in ints:

    #num_list1 = parseint(list1)


for i in num_list:


The file contains:



What my code is about is that it contains the scores for the game and I want my program to sort them alphabetically. Can someone fix my problem?

Note. Some part of the code is not used in the program.


source to share

2 answers

Your input has a "," at the end, which causes split () to generate an empty string in addition to the scores:

['user-1', 'aaa-1', 'usr-3', 'aaa-4', '']



does not work; you must either remove this empty line or process it.



int () cannot accept an empty string, which is an invalid parameter for it. You will need to check if the string is empty when you get it as an int. You can do it in a list comprehension like this:

[int(x) if not (x.isspace() or x == '') else 0 for x in string.split("-")]


You can replace 0 with None or some other result if you like, but this basically always checks that the string is not just whitespace characters using the string.isspace () function and also ensures that x is not an empty string.



All Articles