So I'm certain I've committed a cardinal sin of some kind to have this kind of error, but basically I chopped up a file and converted it wordwise into a list. In this program, I run a function to change everything in the list into an integer, and if it can't be changed, I skip over it. Afterwards, I append every integer to a new list as long as it is larger than 999.
For the next part, I need a standardized length, and python automatically removes leading zeroes, so my idea was to convert the integers back to a string, find their length, and add zeroes up to 10 digits, but regardless of what I try I keep getting:
<class 'str'>
Traceback (most recent call last):
File "phdirDEBUG.py", line 48, in <module>
if len(i) == 10:
TypeError: object of type 'int' has no len()
Note the class str, I even check right before I run the leading zeroes adding function to make sure that the item in the list is a string, yet the error log still says it's an integer. I feel like there is a best practice I'm missing here.
#Puts file into a list word by word.
for eachWord in error_file:
error_lst.extend(eachWord.split())
def str_to_int():
#Converts all string values to integers
for i in range(0, len(error_lst)):
try:
error_lst[i] = int(error_lst[i])
return error_lst
except:
continue
#Everything that is converted to an integer is added to a new list
int_lst = []
for eachword in str_to_int():
if type(eachword) == int and eachword > 999:
int_lst.append(eachword)
def int_to_string():
#And then turned back into a string.
for i in range(0, len(int_lst)):
try:
int_lst[i] = str(int_lst[i])
return int_lst
except:
print("Error converting integer to a string!")
print(type(int_to_string()[0]))
for i in range(0, len(int_to_string())):
if len(i) == 10:
continue
elif len(i) == 9:
i.zfill(1)
elif len(i) == 8:
i.zfill(2)
elif len(i) == 7:
i.zfill(3)
elif len(i) == 6:
i.zfill(4)
elif len(i) == 5:
i.zfill(5)
elif len(i) == 4:
i.zfill(6)
else:
print("This is awkward. I didn't expect there to be an invoice number less than 4 characters long. :/")
CodePudding user response:
if you are trying to itarate over int_list, you can just write:
for i in int_to_string():
no need to use the range here. there is still a problem with your code in the int_to_string function. the return statement will stop the function at the first element that can be converted to string.