Exercise
Function To Alter A Character In A String
Objective
Develop a Python program with a function called "change_char" to alter a character at a specific position (0-based index) in a string, replacing it with another character.
For example:
sentence = "Tomato" change_char(sentence, 5, "a")
Example Python Exercise
Show Python Code
# Define the function to change a character at a specific position
def change_char(sentence, position, new_char):
# Convert the string to a list of characters (since strings are immutable)
sentence_list = list(sentence)
# Replace the character at the specified position with the new character
sentence_list[position] = new_char
# Convert the list back to a string and return it
return ''.join(sentence_list)
# Main function to test the change_char function
def main():
sentence = "Tomato"
# Call change_char to replace the character at index 5 with 'a'
result = change_char(sentence, 5, "a")
print(result) # Expected output: "Tomata"
# Call the main function to execute the program
main()
Output
Tomata
Share this Python Exercise