Thursday 26 November 2020

Choosing which elements to replace in Python

When I use the replace function I can input an additional 3rd argument which describes how many occurences of the particular character I might want to change.

For Example -

input_string = input()
first_char = input_string[0]
modified_string = input_string.replace(first_char, "$", input_string.count(first_char)-1)
print(modified_string)

The above code gives the following output:

Input: heyhhdh
Output: $ey$$dh

It replaced the h starting from the first occurrence but is there a way where I can specify where to start?

For instance in the problem I'm working on I need to leave the first character so is there a way to specify that in python

Edit: The following line of code commented by Tarique performs my task

modified_string = first_char + input_string[1:].replace(first_char, "$", input_string.count(first_char)-1)

However is there a way to do this using only string functions like modifying the arguments in the replace function?



from Choosing which elements to replace in Python

No comments:

Post a Comment