I'd like to share something with a chemical formula. For example
C14H19NO, C10H12O2, C15H26O
to
{"C14","H19","N","O","C10","H12","O2","C15","H26","O"} like this
I also want to know how to process .txt at once please help me..
num=["1","2","3","4","5","6","7","8","9","0"]
text=input("C9H8Cl3")
lis=list(text)
for i in range(len(text)):
if lis[i] in num: lis[i]=int(lis[i])
lis2=lis[:]
k=1
for i in range(len(text)-1):
if type(lis[i])==int and type(lis[i 1])==str:
lis2.insert(i k, "|")
k =1
for i in range(len(lis2)):
if type(lis2[i])==int: lis2[i]=str(lis2[i])
result=""
for i in range(len(lis2)):
result =lis2[i]
print(result)
I tried this, but only one can be converted at a time, and neither is converted.
I want another code.. help me
CodePudding user response:
Generally, we can use re.findall
here:
import re
inp = ["C14H19NO", "C10H12O2", "C15H26O"]
for f in inp:
atoms = re.findall(r'[A-Z][a-z]?[0-9]*', f)
print(atoms)
This prints:
['C14', 'H19', 'N', 'O']
['C10', 'H12', 'O2']
['C15', 'H26', 'O']