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)) 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))
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)
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:
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)
|