2016-06-20 41 views
0

我的意图是使用索引方法在字符串中搜索冒号(:)或等号(=)并打印该字符后的所有内容,但是我意识到它不是语法上可能,因为它在下面用OR语句写成。那么是否有另一种方法来编写这段代码? (我不能拿出一个简单的方法来写这个没有进入循环和if语句)打印字符串中几个特定字符后的所有内容

l='Name = stack' 
pos=l.index(':' or '=') 
print (' '.join(l[pos+1:-1].split())) #this just gets rid of the whitespaces 
+0

'IND = l.index( “:”);如果ind == -1:ind = l.index(“=”); print(l [pos + 1:])'或者非常可能'print(l [max([l.index(“:”),l.index(“=”)])+ 1:])'这实际上是不可读的。点是 - 你需要将'.index()'分成两个单独的测试 – dwanderson

+0

''''或'=''评估为'':'' –

回答

2

假设你的例子如上述,在很长的路要走(每片的解释如下):

pos = max(l.find(':'), l.find('='), 0)  
print(l[pos:].strip())  

下面就来缩短到一条线的方式,用它在真实评价的顺序各部分的说明。

print(l[max(l.find(':'),l.find('='),0):].strip()) 
#--------------- Breakdown 
# max -> highest of values; find returns -1 if it isn't there. 
#  using a 0 at the end means if ':'/'=' aren't in the string, print the whole thing. 
# l.find(),l.find() -> check the two characters, using the higher due to max() 
# l[max():] -> use that higher value until the end (implied with empty :]) 
# .strip() -> remove whitespace    
+0

感谢您的分解!只是一个fyi,如果字符串不存在,则查找返回-1,并且索引引发异常。 – Neil

+0

是的,没问题;感谢编辑的答案。 – Delioth

2
import re 

l='Name = stack' 
print(re.split(':|=', l)[-1]) 

则表达式分割上为字符,然后采取最后的结果。

你没有提及是否有保证是一个或另一个分隔符,而不是两个,总是一个分隔符,不超过一个分隔符......这可能不会做你想要的,取决于。

1

你应该拆分的数量限制为一体,采用maxsplitre.split()

import re 

s1 = 'name1 = x1 and noise:noise=noise' 
s2 = 'name2: x2 and noise:noise=noise' 
print(re.split(':|=', s1, maxsplit=1)[-1].strip()) 
print(re.split(':|=', s2, maxsplit=1)[-1].strip()) 

输出:

x1 and noise:noise=noise 
x2 and noise:noise=noise 
相关问题