[英]How to ignore some part of a line using python?
S1C(SCC1)C1=COC2C(C{OC}C3C(OC=C3)C2)C1=O
S1C(SCC1)C1 = COC2C(C {OC} C3C(OC = C3)C2)C1 = O
In the above string, I want the program to ignore {OC} or technically anything in between these flower brackets but work normally with rest of the string. 在上面的字符串中,我希望程序忽略{OC}或技术上在这些花括号之间的任何内容,但可以正常处理其余字符串。 I have a file which thousands of such strings.
我有一个文件,其中有数千个这样的字符串。 Some strings have more than one set of flower brackets.
有些琴弦有多个花括号。 How should it be done?
应该怎么做?
Presently I use python 2.5
version. 目前,我使用
python 2.5
版本。
This might help. 这可能会有所帮助。 Using regex.
使用正则表达式。
import re
s = "S1C(SCC1)C1=COC2C(C{OC}C3C(OC=C3)C2)C1=O"
print re.sub("\{(.*?)\}", " ", s) #Replacing curly brackets and its content by space.
Output: 输出:
S1C(SCC1)C1=COC2C(C C3C(OC=C3)C2)C1=O
You can use string slicing for this. 您可以为此使用字符串切片。
Note - This will work correctly only if you have one such bracket in string 注意-仅当字符串中有一个这样的括号时,此方法才能正常工作
str = "S1C(SCC1)C1=COC2C(C{OC}C3C(OC=C3)C2)C1=O"
startofbracket = str.find("{")
endofbracket = str.find("}")
print str[:startofbracket]+str[endofbracket+1:]
You can iterate over the string and keep track of characters that are not in between brackets. 您可以遍历字符串并跟踪不在方括号之间的字符。 The following code assumes no '{' character inside the string
以下代码假定字符串内没有'{'字符
string = "S1C(SCC1)C1=COC2C(C{OC}C3C(OC=C3)C2)C1=O"
output = ""
brace_found = False
for i in range(len(string)):
if brace_found:
if string[i] == "}":
brace_found = False
else:
if string[i] != "{":
output+=string[i]
else:
brace_found = True
print output
# S1C(SCC1)C1=COC2C(CC3C(OC=C3)C2)C1=O
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.