By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,952 Members | 1,937 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,952 IT Pros & Developers. It's quick & easy.

search and replace with variable value

P: 16
I've to search for a pattern and replace with input variable.
Suppose the strings are:

tempSearch : = '111-452-05'
tempSearch:= '111-452-10'
tempSearch:='111-459-15'
tempSearch: ='111-452-20'
tempSearch:='111-452-25'

search for the whole pattern starting from the "temp" to the end "'". I've to replace the value that is occuring after the first appearance of "-" with a user input value.

How can I do it?

Thank You!
Mar 11 '14 #1
Share this Question
Share on Google+
3 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Using str methods only:
Expand|Select|Wrap|Line Numbers
  1. >>> s = "tempSearch : = '111-452-05'"
  2. >>> userStr = "XYZ"
  3. >>> s[:s.index("-")+1]+userStr
  4. "tempSearch : = '111-XYZ"
  5. >>> 
Using re and str methods:
Expand|Select|Wrap|Line Numbers
  1. >>> import re
  2. >>> s = "tempSearch : = '111-452-05'"
  3. >>> userStr = "XYZ"
  4. >>> patt = re.compile(r"-(.+)")
  5. >>> m = patt.search(s)
  6. >>> s.replace(m.group(1), userStr)
  7. "tempSearch : = '111-XYZ"
  8. >>> 
Mar 11 '14 #2

Expert 100+
P: 613
Take a look at "Searching Text" and "Replacing Text" at http://www.freenetpages.co.uk/hp/alan.gauld/tuttext.htm You can also split on the "-" if that is easier to understand.
Expand|Select|Wrap|Line Numbers
  1. testing="tempSearch : = '111-452-05'"
  2. replaced = "new part"
  3. parts = testing.split("-")
  4. print "parts =", parts
  5. parts[1]=replaced
  6. print "-".join(parts) 
Mar 11 '14 #3

P: 16
Thanks for the reply guys!!!
Mar 17 '14 #4

Post your reply

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