473,396 Members | 1,712 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Searching through a list and replacing items in it...

Thekid
145 100+
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.

Expand|Select|Wrap|Line Numbers
  1. f = open("numbers.txt","r")
  2. contents = f.read( )
  3. # I'm not sure why the .split is in here but someone suggested it to me so I 
  4. # included it. I could .split("%") but then what?
  5. fields = contents.split(",")
  6. print fields
  7.  

# 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:
Expand|Select|Wrap|Line Numbers
  1. f = open("numbers.txt","r")
  2. contents = f.read( )
  3. data = contents.split(",")
  4. if data.find("%"):
  5. print "Symbol found"
  6.  
^ gets error message because the .split puts it into a list. I also tried re.search("%").

Any suggestions?
Feb 20 '08 #1
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.

Expand|Select|Wrap|Line Numbers
  1. f = open("numbers.txt","r")
  2. contents = f.read( )
  3. # I'm not sure why the .split is in here but someone suggested it to me so I 
  4. # included it. I could .split("%") but then what?
  5. fields = contents.split(",")
  6. print fields
  7.  

# 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:
Expand|Select|Wrap|Line Numbers
  1. f = open("numbers.txt","r")
  2. contents = f.read( )
  3. data = contents.split(",")
  4. if data.find("%"):
  5. print "Symbol found"
  6.  
^ 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.
Expand|Select|Wrap|Line Numbers
  1. def replace_pos(s, old, new, posList):
  2.     idx = -1
  3.     count = 0
  4.     while True:
  5.         '''
  6.         s.find() returns the position of the substring.
  7.         When the end of string is reached and no more
  8.         occurrances of substring are found, s.find()
  9.         returns -1.
  10.         '''
  11.         idx = s.find(old, idx+1)
  12.         count += 1
  13.         if idx == -1:
  14.             return s
  15.         elif count in posList:
  16.             s = '%s%s%s' % (s[:idx],new,s[(idx+len(old)):])   
  17.  
  18. fn = r'H:\TEMP\temsys\numbers1.txt'
  19. s = open(fn).read()
  20. oldStr = '%'
  21. newStr = '$'
  22. posList = [1,5,13]
  23. 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.
Feb 21 '08 #2
Thekid
145 100+
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?
Feb 22 '08 #3
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.
Expand|Select|Wrap|Line Numbers
  1. s2 = s.replace('%', '$')
Feb 22 '08 #4
Thekid
145 100+
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....
Feb 22 '08 #5
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.
Feb 22 '08 #6
Thekid
145 100+
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:

Expand|Select|Wrap|Line Numbers
  1. def replace_pos(s, old, new, posList):
  2.     idx = -1
  3.     count = 0
  4.     while True:
  5.         '''
  6.         s.find() returns the position of the substring.
  7.         When the end of string is reached and no more
  8.         occurrances of substring are found, s.find()
  9.         returns -1.
  10.         '''
  11.         idx = s.find(old, idx+1)
  12.         count += 1
  13.         if idx == -1:
  14.             return s
  15.         elif count in posList:
  16.             s = '%s%s%s' % (s[:idx],new,s[(idx+len(old)):])   
  17.  
  18. # I changed this part slightly
  19. fn = open("numbers.txt","r")
  20. s = (fn).read()
  21. oldStr = "#"
  22. newStr = "@"
  23. posList = [1,2,3]
  24. s1 = s.replace("%","#")
  25. s2 = replace_pos(s1, oldStr, newStr, posList)
  26. print s2
  27.  
  28.  
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:


Expand|Select|Wrap|Line Numbers
  1.  
  2. solution = s2
  3. f 2= open("numbers.txt","w")
  4. f2.write(solution)
  5. f2.close
  6. print solution
  7.  
Feb 25 '08 #7
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:

Expand|Select|Wrap|Line Numbers
  1. def replace_pos(s, old, new, posList):
  2.     idx = -1
  3.     count = 0
  4.     while True:
  5.         '''
  6.         s.find() returns the position of the substring.
  7.         When the end of string is reached and no more
  8.         occurrances of substring are found, s.find()
  9.         returns -1.
  10.         '''
  11.         idx = s.find(old, idx+1)
  12.         count += 1
  13.         if idx == -1:
  14.             return s
  15.         elif count in posList:
  16.             s = '%s%s%s' % (s[:idx],new,s[(idx+len(old)):])   
  17.  
  18. # I changed this part slightly
  19. fn = open("numbers.txt","r")
  20. s = (fn).read()
  21. oldStr = "#"
  22. newStr = "@"
  23. posList = [1,2,3]
  24. s1 = s.replace("%","#")
  25. s2 = replace_pos(s1, oldStr, newStr, posList)
  26. print s2
  27.  
  28.  
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:


Expand|Select|Wrap|Line Numbers
  1.  
  2. solution = s2
  3. f 2= open("numbers.txt","w")
  4. f2.write(solution)
  5. f2.close
  6. print solution
  7.  
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.
Expand|Select|Wrap|Line Numbers
  1. comb_list = [[1,2,3], [1,2,4], [1,2,5], [1,3,4], [1,4,5], [2,3,4], [3,4,5]]
  2.  
  3. for clist in comb_list:
  4.     s1 = replace_pos(s, oldStr, newStr, clist)
Feb 25 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

9
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,...
4
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...
3
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: ...
33
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...
2
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...
7
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...
14
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...
37
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.
20
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:...
0
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...
0
BarryA
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
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...
0
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...
0
marktang
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,...
0
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...
0
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...
0
tracyyun
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.