+ 1
Python ValueError (sorting a sentence)
I get the this error: ValueError: invalid literal for int() with int() with base 10. The line python complains about works perfectly if I print it. But when I insert the last line I get the error. I can't understand it. Thanks for all help and replies. https://code.sololearn.com/c449oP9r2JTu/?ref=app
4 ответов
+ 5
mariusep ,
we could also use sorting to solve the task.
since the last character of each word is a digit that defines the word sequence of the final string, we can use sorted() with the *key* argument as a lambda.
key=lambda word: word[-1]
this means that not the entire word will be used for sorting, only the last character.
+ 2
In the first iteration, you set the sentence[1] to "is". Accordingly, the second iteration will no longer consider "Python3", but "is" and the num will be set to "s", hence the error: int("s").
+ 1
sentence = ["is2","Python3","This1"]
new_sentence = sentence.copy() #add it
for word in sentence:
num = word[-1]
new_word = word[:-1]
index = int(num)-1
new_sentence[index]=new_word #sentence[index]=new_word
print(sentence)
print(new_sentence)
+ 1
It all make sense now! Thanks