如果您有字符串的开始和结束索引,则可以执行以下操作:
substring = string[s_ind:e_ind]
wheres_ind
是您要包含在字符串e_ind
中的第一个字符的索引,并且是您不希望包含在字符串中的第一个字符的索引。
例如
string = "Long string of which I only want a small part"
# 012345678901234567890123456789012345678901234
# 0 1 2 3
substring = string[21:32]
print substring
印刷I only want
您可以像现在一样找到索引。
编辑:关于效率,这种类型的解决方案实际上比正则表达式解决方案更有效。原因是您不一定需要的正则表达式涉及大量开销。
我鼓励你自己测试这些东西,而不是盲目地去做人们声称最有效的东西。
考虑以下测试程序:
#!/bin/env python
import re
import time
def inner_regex(s):
return re.sub(r'<[^>]*>', '', s)
def inner_substr(s):
s_ind = s.find('>') + 1
e_ind = s.find('<', s_ind)
return s[s_ind:e_ind]
s = '<stuff to remove> get this stuff <stuff to remove>'
tr1 = time.time()
for i in range(100000):
s1 = inner_regex(s)
tr2 = time.time()
print("Regex: %f" % (tr2 - tr1))
ts1 = time.time()
for i in range(100000):
s2 = inner_substr(s)
ts2 = time.time()
print("Substring: %f" % (ts2 - ts1))
输出是:
Regex: 0.511443
Substring: 0.148062
换句话说,使用正则表达式方法比原来的更正方法慢3 倍以上。
编辑:关于已编译正则表达式的评论,它比未编译的正则表达式快,但仍比显式子字符串慢:
#!/bin/env python
import re
import time
def inner_regex(s):
return re.sub(r'<[^>]*>', '', s)
def inner_regex_compiled(s,r):
return r.sub('', s)
def inner_substr(s):
s_ind = s.find('>') + 1
e_ind = s.find('<', s_ind)
return s[s_ind:e_ind]
s = '<stuff to remove> get this stuff <stuff to remove>'
tr1 = time.time()
for i in range(100000):
s1 = inner_regex(s)
tr2 = time.time()
tc1 = time.time()
r = re.compile(r'<[^>]*>')
for i in range(100000):
s2 = inner_regex_compiled(s,r)
tc2 = time.time()
ts1 = time.time()
for i in range(100000):
s3 = inner_substr(s)
ts2 = time.time()
print("Regex: %f" % (tr2 - tr1))
print("Regex Compiled: %f" % (tc2 - tc1))
print("Substring: %f" % (ts2 - ts1))
回报:
Regex: 0.512799 # >3 times slower
Regex Compiled: 0.297863 # ~2 times slower
Substring: 0.144910
故事的寓意:虽然正则表达式是工具箱中的一个有用工具,但它们根本不如可用的更直接的方法高效。
并且不要相信别人的话,你可以很容易地测试自己。