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]
#3
(Aug-06-2021, 09:05 PM)bowlofred Wrote: If it's not too huge, I'd just loop over it. But for very large files, that's inefficient.

paragraph = """This example is an example on how to make an
example with the word example. the example ends here with an example. for example"""

target = "example"
counter = 0
while target in paragraph:
    counter += 1
    paragraph = paragraph.replace(target, str(counter), 1)

print(paragraph)
If it is huge, time to break out regex parser. I think there should be a simpler way to write a callable incrementor, but this will do for now.

import re

target = "example"

def str_counter(match_object):
    str_counter.count += 1
    return str(str_counter.count)
str_counter.count = 0

paragraph = """This example is an example on how to make an
example with the word example. the example ends here with an example. for example"""

paragraph = re.sub(re.escape(target), str_counter, paragraph)

print(paragraph)

Hey, thanks for replying.
Where do I have to define that my script should check in text-files? And what's the difference between target and paragraph?
Reply


Messages In This Thread
RE: Replace String with increasing numer - by AlphaInc - Aug-06-2021, 09:13 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 814 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Replace string in a nested Dictianory. SpongeB0B 2 1,271 Mar-24-2023, 05:09 PM
Last Post: SpongeB0B
  Replace with upper(string) WJSwan 7 1,664 Feb-10-2023, 10:28 AM
Last Post: WJSwan
  [SOLVED] [BeautifulSoup] Why does it turn inserted string's brackets into </>? Winfried 0 1,573 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,290 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,290 Oct-21-2021, 11:28 AM
Last Post: EnfantNicolas
  Replace String in multiple text-files [SOLVED] AlphaInc 5 8,269 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