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]
#1
Hello everybody,

I have a text-file with multiple strings which I want to be replaced by an increasing number.
For example there is there the string "example" 7 times in it and I want to replace "example" with a number:

Before:
This example is an example on how to make an example with the word example. the example ends here with an example. for example.

After
This 1 is an 2 on how to make an 3 with the word 4. the 5 ends here with an 6. for 7.

How do you do that?
Also, while developing the script, I want it to look for every text-file inside my folder not just a specified file (see code below).

This is what I have now but it doens't work:

#!/usr/bin/env python3

fileCounter = 1

with open('*.txt', 'r') as file :
  filedata = file.read()

filedata = filedata.replace('example', ''+fileCounter)

with open('*.txt', 'w') as file:
  file.write(filedata)
Reply


Messages In This Thread
Replace String with increasing numer [SOLVED] - by AlphaInc - Aug-06-2021, 08:31 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 795 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Replace string in a nested Dictianory. SpongeB0B 2 1,240 Mar-24-2023, 05:09 PM
Last Post: SpongeB0B
  Replace with upper(string) WJSwan 7 1,625 Feb-10-2023, 10:28 AM
Last Post: WJSwan
  [SOLVED] [BeautifulSoup] Why does it turn inserted string's brackets into </>? Winfried 0 1,553 Sep-03-2022, 11:21 PM
Last Post: Winfried
  [SOLVED] [BeautifulSoup] Turn select() into comma-separated string? Winfried 0 1,133 Aug-19-2022, 08:07 PM
Last Post: Winfried
  Find and Replace numbers in String giddyhead 2 1,260 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  Adding string after every 3rd charater [SOLVED] AlphaInc 2 1,298 Jul-11-2022, 09:22 AM
Last Post: ibreeden
Question [SOLVED] Delete specific characters from string lines EnfantNicolas 4 2,267 Oct-21-2021, 11:28 AM
Last Post: EnfantNicolas
  Replace String in multiple text-files [SOLVED] AlphaInc 5 8,225 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,309 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