Hi, I need to search through a given file and find certain keys and replace them, in this case it's the symbol "%". I'm not sure how to go about this. -
f = open("numbers.txt","r")
-
contents = f.read( )
-
# I'm not sure why the .split is in here but someone suggested it to me so I
-
# included it. I could .split("%") but then what?
-
fields = contents.split(",")
-
print fields
-
# numbers.txt=
1234435%357435734763736%474526435151463267%2394324 9023403478234724234782347234234247824273423478235% 4728340723840%472347234023742%72304372104%472389%4 7204
47242%7420472394729472472390427472482%742947247289 04273%34%
21211212122121%1121212121%67676767676767%878787878 78787%
I can print the file out like this but I need to replace the 1st, 5th & 13th "%" with "$".
I tried to do something like this to see if it would just find "%" but it didn't work: -
f = open("numbers.txt","r")
-
contents = f.read( )
-
data = contents.split(",")
-
if data.find("%"):
-
print "Symbol found"
-
^ gets error message because the .split puts it into a list. I also tried re.search("%").
Any suggestions?
7 1608 bvdet 2,851
Expert Mod 2GB
Hi, I need to search through a given file and find certain keys and replace them, in this case it's the symbol "%". I'm not sure how to go about this. -
f = open("numbers.txt","r")
-
contents = f.read( )
-
# I'm not sure why the .split is in here but someone suggested it to me so I
-
# included it. I could .split("%") but then what?
-
fields = contents.split(",")
-
print fields
-
# numbers.txt=
1234435%357435734763736%474526435151463267%2394324 9023403478234724234782347234234247824273423478235% 4728340723840%472347234023742%72304372104%472389%4 7204
47242%7420472394729472472390427472482%742947247289 04273%34%
21211212122121%1121212121%67676767676767%878787878 78787%
I can print the file out like this but I need to replace the 1st, 5th & 13th "%" with "$".
I tried to do something like this to see if it would just find "%" but it didn't work: -
f = open("numbers.txt","r")
-
contents = f.read( )
-
data = contents.split(",")
-
if data.find("%"):
-
print "Symbol found"
-
^ gets error message because the .split puts it into a list. I also tried re.search("%").
Any suggestions?
String methods can be used to accomplish your task. - def replace_pos(s, old, new, posList):
-
idx = -1
-
count = 0
-
while True:
-
'''
-
s.find() returns the position of the substring.
-
When the end of string is reached and no more
-
occurrances of substring are found, s.find()
-
returns -1.
-
'''
-
idx = s.find(old, idx+1)
-
count += 1
-
if idx == -1:
-
return s
-
elif count in posList:
-
s = '%s%s%s' % (s[:idx],new,s[(idx+len(old)):])
-
-
fn = r'H:\TEMP\temsys\numbers1.txt'
-
s = open(fn).read()
-
oldStr = '%'
-
newStr = '$'
-
posList = [1,5,13]
-
s1 = replace_pos(s, oldStr, newStr, posList)
There is no need to split the string into a list, although there is a way to get the same result.
Great, thank you that works. Now what if I need to change all of them instead of just a few, but don't know how many are in the file? How can I replace them all?
bvdet 2,851
Expert Mod 2GB
Great, thank you that works. Now what if I need to change all of them instead of just a few, but don't know how many are in the file? How can I replace them all?
That's much easier.
Once again thanks, that does the trick. One last question regarding this, what about a loop that will go through and try various combinations? For example, let's say it will replace positions 1,2,3 then try 1,2,4, then try 1,2,5 etc....
bvdet 2,851
Expert Mod 2GB
Once again thanks, that does the trick. One last question regarding this, what about a loop that will go through and try various combinations? For example, let's say it will replace positions 1,2,3 then try 1,2,4, then try 1,2,5 etc....
The function replace_pos() should work for that.
The function replace_pos() should work for that.
I've played around with the replace_pos() but still can't seem to get it to work as a loop. This is it so far: -
def replace_pos(s, old, new, posList):
-
idx = -1
-
count = 0
-
while True:
-
'''
-
s.find() returns the position of the substring.
-
When the end of string is reached and no more
-
occurrances of substring are found, s.find()
-
returns -1.
-
'''
-
idx = s.find(old, idx+1)
-
count += 1
-
if idx == -1:
-
return s
-
elif count in posList:
-
s = '%s%s%s' % (s[:idx],new,s[(idx+len(old)):])
-
-
# I changed this part slightly
-
fn = open("numbers.txt","r")
-
s = (fn).read()
-
oldStr = "#"
-
newStr = "@"
-
posList = [1,2,3]
-
s1 = s.replace("%","#")
-
s2 = replace_pos(s1, oldStr, newStr, posList)
-
print s2
-
-
This is taking the 'numbers.txt' and first replacing all of the '%' symbols with '#'. It then replaces the 1,2,3 '#' symbols with '@'. What I want to do is first change all of the symbols but then have a loop replace the 1,2,3 symbols. If they are the correct combinations then it's done, if not I need the code to replace the 1,2,4 positions, then 1,2,5 and so on until all combinations are checked. Also, I can 'write' to the file by adding the code below but it doesn't fit in to the loop because it saves the changes and that throws off the next run through of the code: -
-
solution = s2
-
f 2= open("numbers.txt","w")
-
f2.write(solution)
-
f2.close
-
print solution
-
bvdet 2,851
Expert Mod 2GB
I've played around with the replace_pos() but still can't seem to get it to work as a loop. This is it so far: -
def replace_pos(s, old, new, posList):
-
idx = -1
-
count = 0
-
while True:
-
'''
-
s.find() returns the position of the substring.
-
When the end of string is reached and no more
-
occurrances of substring are found, s.find()
-
returns -1.
-
'''
-
idx = s.find(old, idx+1)
-
count += 1
-
if idx == -1:
-
return s
-
elif count in posList:
-
s = '%s%s%s' % (s[:idx],new,s[(idx+len(old)):])
-
-
# I changed this part slightly
-
fn = open("numbers.txt","r")
-
s = (fn).read()
-
oldStr = "#"
-
newStr = "@"
-
posList = [1,2,3]
-
s1 = s.replace("%","#")
-
s2 = replace_pos(s1, oldStr, newStr, posList)
-
print s2
-
-
This is taking the 'numbers.txt' and first replacing all of the '%' symbols with '#'. It then replaces the 1,2,3 '#' symbols with '@'. What I want to do is first change all of the symbols but then have a loop replace the 1,2,3 symbols. If they are the correct combinations then it's done, if not I need the code to replace the 1,2,4 positions, then 1,2,5 and so on until all combinations are checked. Also, I can 'write' to the file by adding the code below but it doesn't fit in to the loop because it saves the changes and that throws off the next run through of the code: -
-
solution = s2
-
f 2= open("numbers.txt","w")
-
f2.write(solution)
-
f2.close
-
print solution
-
You need to have some way to determine the replacement position lists. What are "all combinations"? After you create the all combinations list, then you can iterate on that list. - comb_list = [[1,2,3], [1,2,4], [1,2,5], [1,3,4], [1,4,5], [2,3,4], [3,4,5]]
-
-
for clist in comb_list:
-
s1 = replace_pos(s, oldStr, newStr, clist)
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Jess Austin |
last post by:
hi,
I like the way that Python does lists, and I love the way it does
iterators. But I've decided I don't like what it does with iterators
of lists. Lists are supposed to be mutable sequences,...
|
by: tgiles |
last post by:
Hi, all. Another bewildered newbie struggling with Python goodness. This
time it's searching strings. The goal is to search a string for a value.
The string is a variable I assigned the name...
|
by: googleboy |
last post by:
Hi there.
I have defined a class called Item with several (about 30 I think)
different attributes (is that the right word in this context?). An
abbreviated example of the code for this is:
...
|
by: Geoff Jones |
last post by:
Hiya
I have a DataTable containing thousands of records. Each record has a
primary key field called "ID" and another field called "PRODUCT" I want to
retrieve the rows that satisy the following...
|
by: Richard Brosnahan |
last post by:
I hate asking questions that have probably been answered before, but
I have not found a way to conveniently search the archives of this
mailing list.
So...
Can someone tell me how to...
|
by: MTD |
last post by:
Hello,
I'm wondering if there's a quick way of resolving this problem.
In a program, I have a list of tuples of form (str,int), where int is a
count of how often str occurs
e.g. L = would...
|
by: Ben |
last post by:
I have recently learned how list comprehension works and am finding it
extremely cool. I am worried, however, that I may be stuffing it into
places that it does not belong.
What's the most...
|
by: bahoo |
last post by:
Hi,
I have a list like
and as output I want
If I
myList.remove('0024')
then only the first instance of '0024' is removed.
|
by: Seongsu Lee |
last post by:
Hi,
I have a dictionary with million keys. Each value in the
dictionary has a list with up to thousand integers.
Follow is a simple example with 5 keys.
dict = {1: ,
2: ,
900000: ,
900001:...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
| |