Python Forum
Convert string to int - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Convert string to int (/thread-36377.html)



Convert string to int - Frankduc - Feb-13-2022

Hello,

Trying to sum string numbers to int, but there is a ; between them.

tab = input("Éntrez les nombres entiers séparés par des (;) : ")

list_nb= [tab]
list_nb = [item.replace(";"," ") for item in list_nb]

nbs = list(map(int, list_nb))

somme = 0
for nb in nbs:
    print((somme + nb)/len(nbs))
    
Error:
Éntrez les nombres entiers séparés par des (;) : 4;5;7; Traceback (most recent call last): File "<string>", line 10, in <module> ValueError: invalid literal for int() with base 10: '4 5 7 ' >
Why i get this error. Numbers need to be input with ";"

Thank you


RE: Convert string to int - menator01 - Feb-13-2022

tab = input('Enter numbers seperated with (;) : ') .split(';')
print(tab)

tab = list(map(int, tab))

print(tab)

somme = 0

for number in tab:
    print((somme + number)/len(tab))
Output:
Enter numbers seperated with (;) : 5;9;6;7 ['5', '9', '6', '7'] [5, 9, 6, 7] 1.25 2.25 1.5 1.75



RE: Convert string to int - Frankduc - Feb-13-2022

only thing 5+6+9+7 = 6.75 not 1.75


RE: Convert string to int - menator01 - Feb-13-2022

use sum(tab) instead of len(tab)

Output:
Enter numbers seperated with (;) : 5;6;9;7 ['5', '6', '9', '7'] [5, 6, 9, 7] 0.18518518518518517 0.2222222222222222 0.3333333333333333 0.25925925925925924 6.75



RE: Convert string to int - Yoriz - Feb-13-2022

user_input = input("Éntrez les nombres entiers séparés par des (;) : ")
numbers = [int(item) for item in user_input.split(";")]
print(sum(numbers) / len(numbers))



RE: Convert string to int - Frankduc - Feb-13-2022

Cant use sum in this assignment and its returning error anyway:

Error:
Éntrez les nombres entiers séparés par des (;) : 4;5;5; Traceback (most recent call last): File "<string>", line 6, in <module> File "<string>", line 6, in <listcomp> ValueError: invalid literal for int() with base 10: '' >



RE: Convert string to int - Yoriz - Feb-13-2022

The above error is nothing to do with sum you are trying to turn an empty string into an int
You have a ; at the end of the input string so when the split happens you end up with an empty string as the last list item.


RE: Convert string to int - Frankduc - Feb-13-2022

I got it now. Stupid misunderstanding

Thanks guys


RE: Convert string to int - menator01 - Feb-13-2022

tab = '5;6;9;7'.split(';')
tab = list(map(int, tab))

somme = 0
total = 0

for number in tab:
    total += number
print(f'Sum of tab list is: {total}')

for number in tab:
    print((somme + number)/total)
Output:
Sum of tab list is: 27 0.18518518518518517 0.2222222222222222 0.3333333333333333 0.25925925925925924