Skip to main content
 首页 » 编程设计

python之打印字符串中几个特定字符后的所有内容

2025年05月04日44lovecherry

我的意图是使用索引方法在字符串中搜索冒号 (:) 或等号 (=) 并打印该字符之后的所有内容,但我意识到这在语法上是不可能的,因为它在下面用 OR 语句编写.那么这段代码还有别的写法吗? (如果不进入循环和 if 语句,我无法想出一种简单的方法来编写它)

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

请您参考如下方法:

假设您的示例如上,那么很长的路要走(下面每一部分的解释):

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