String mutation exercise's solution difference explanation
Question:
So I’m new in coding, I solved a string mutation exercise, it is about you take 2 inputs, a position, and a character, you replace the character in the given position with the new character, I solved it by using this
def mutate_string(string, position, character):
x = list(string)
x[position] = character
return "".join(x)
but I have been told to use this other code which is better, my question why it is better?
def mutate_string(string, position, character):
return string[:position] + character + string[position + 1:]
Answers:
Strings are immutable in Python. Hence you can’t replace the character directly. The way you approach the problem requires converting string to list, perform mutation and join the characters back to string (''.join(x)
, which I do not see in your function). Hence, using string slicing is a cleaner approach with lesser overhead.
So I’m new in coding, I solved a string mutation exercise, it is about you take 2 inputs, a position, and a character, you replace the character in the given position with the new character, I solved it by using this
def mutate_string(string, position, character):
x = list(string)
x[position] = character
return "".join(x)
but I have been told to use this other code which is better, my question why it is better?
def mutate_string(string, position, character):
return string[:position] + character + string[position + 1:]
Strings are immutable in Python. Hence you can’t replace the character directly. The way you approach the problem requires converting string to list, perform mutation and join the characters back to string (''.join(x)
, which I do not see in your function). Hence, using string slicing is a cleaner approach with lesser overhead.