Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python replace nth occurrence in string

my_string = "This is a long string that contain a string about a string"

# I want to replace the second "string" with "text"

nth = 2  

my_string = my_string.replace("string", "text", nth)
my_string = my_string.replace("text", "string", nth-1)
# >>> my_string == "This is a long string that contain a text about string"
 
PREVIOUS NEXT
Tagged: #python #replace #nth #occurrence #string
ADD COMMENT
Topic
Name
8+8 =