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

How to replace several different characters in text file using asterisk in python?

P: 1
I try to delete from text file those characters '{a}' '{b}' ... and so on (i have 250 curly braces in the text file) using this code:

Expand|Select|Wrap|Line Numbers
  1. # -*- coding: cp1255 -*-
  2. import sys,codecs,string
  4. reload(sys)
  5. sys.setdefaultencoding('utf8')
  6. root = r"G:\desktop\y\test2.txt"
  7. x = open(root)
  9. x.close()
  10. x=open(root,"w")
  11. x.write(s)
  12. x.close
because the letters change in every curly brackets i used asterisk in the,

but after i run this code nothing change in the text file:

>>> ================================ RESTART ================================
Jan 21 '20 #1
Share this Question
Share on Google+
2 Replies

Expert 100+
P: 1,038
It's not clear what you are trying to do.

Can you provide a minimum example of you filterfile (test2.txt), and and what you expect as output?
4 Weeks Ago #2

P: 94
How about using "re.sub"?
Here is an example to delete characters '{a}' '{b}' '-'
Expand|Select|Wrap|Line Numbers
  1. import re
  2. text = "aaaaaa{a}-bbbbbbb{b}-ccccc{c}-dddddd{d}."
  3. text_mod = re.sub('\{[a-b]\}','',text).replace('-','')
  4. print (text_mod)
result :aaaaaabbbbbbbccccc{c}dddddd{d}.
4 Weeks Ago #3

Post your reply

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