Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing specific symbol in a string in python, LaTeX to HTML without converter

I have a string, w, and I want to replace "$_" with "<sub>" and the first "$" after "$_" with "</sub>". I need to do the same with replacing "$^" with "<sup>" and the "$" after it with "</sup>". I tried w.replace("$_", "<sub>") and w.replace("$", "</sub>"), but I can't get only the first "$" after "$_" to be replaced with "</sub>", only every "$" after it. The same follows for replacing "$^" with "<sup>". How can I call only the "$" directly after the "$_" or "$^" indicators to change and not the rest?

Python code:

w = ["Li$_3$O$^cat$", "Al$_2$O$_3$", "ZnO", "H$_2$O+O$^3$"]
w = str(w)
if '$_' in w:
    w = w.replace("$_", "<sub>") 
    w = w.replace("$", "</sub>") 

if '$^' in w: 
    w = w.replace("$^","<sup>")
    w = w.replace("$","</sup>") 

print w

Desired output:

['Li< sub >3< /sub >O< sup >cat< /sup >', 
 'Al< sub >2< /sub >O< sub >3< /sub >', 
 'ZnO', 
 'H< sub >2< /sub >O+O< sup >3< /sup >']
like image 266
Zach Thomas Avatar asked Mar 22 '26 04:03

Zach Thomas


1 Answers

With regex, you can replace only the first occurrence using count=1 parameter, with those 2 statements:

w = re.sub(r"\$_","<sub>",w,count=1)
w = re.sub(r"\$","</sub>",w,count=1)

(note the escaping of the $ sign)

Another way is to use str.partition which splits according to left part, separator, right part, and rebuild a string using a new separator:

parts = w.partition("$_")
w = parts[0]+"<sub>"+parts[2]
parts = w.partition("$")
w = parts[0]+"</sub>"+parts[2]

or

w = "<sub>".join(w.partition("$_")[::2])
w = "</sub>".join(w.partition("$")[::2])
like image 62
Jean-François Fabre Avatar answered Mar 23 '26 18:03

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!