Python Forum
Replace String with increasing numer [SOLVED]
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replace String with increasing numer [SOLVED]
#4
maybe like this?

mytext = """hello example
example test
world example
example to learn
best example
example new
better example"""

result = ""

filedata = mytext.splitlines()

i = 1
for line in filedata: 
    if 'example' in line:
        line = line.replace("example", f"example_{str(i)}")
        i += 1
    result += f"{line}\n"

print(result)
Output:
hello example_1 example_2 test world example_3 example_4 to learn best example_5 example_6 new better example_7
Reply


Messages In This Thread
RE: Replace String with increasing numer - by Axel_Erfurt - Aug-06-2021, 09:16 PM
RE: Replace String with increasing numer - by Yoriz - Aug-06-2021, 10:11 PM
RE: Replace String with increasing numer - by Yoriz - Aug-06-2021, 11:01 PM
RE: Replace String with increasing numer - by Yoriz - Aug-06-2021, 11:25 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Need to replace a string with a file (HTML file) tester_V 1 811 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Replace string in a nested Dictianory. SpongeB0B 2 1,268 Mar-24-2023, 05:09 PM
Last Post: SpongeB0B
  Replace with upper(string) WJSwan 7 1,663 Feb-10-2023, 10:28 AM
Last Post: WJSwan
  [SOLVED] [BeautifulSoup] Why does it turn inserted string's brackets into </>? Winfried 0 1,572 Sep-03-2022, 11:21 PM
Last Post: Winfried
  [SOLVED] [BeautifulSoup] Turn select() into comma-separated string? Winfried 0 1,151 Aug-19-2022, 08:07 PM
Last Post: Winfried
  Find and Replace numbers in String giddyhead 2 1,287 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  Adding string after every 3rd charater [SOLVED] AlphaInc 2 1,319 Jul-11-2022, 09:22 AM
Last Post: ibreeden
Question [SOLVED] Delete specific characters from string lines EnfantNicolas 4 2,287 Oct-21-2021, 11:28 AM
Last Post: EnfantNicolas
  Replace String in multiple text-files [SOLVED] AlphaInc 5 8,267 Aug-08-2021, 04:59 PM
Last Post: Axel_Erfurt
Thumbs Up Parsing a YAML file without changing the string content..?, Flask - solved. SpongeB0B 2 2,327 Aug-05-2021, 08:02 AM
Last Post: SpongeB0B

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020