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

标签 python python-3.x

我的意图是使用索引方法在字符串中搜索冒号 (:) 或等号 (=) 并打印该字符之后的所有内容,但我意识到这在语法上是不可能的,因为它在下面用 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              

关于python - 打印字符串中几个特定字符后的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37932006/

相关文章:

python - SQLAlchemy 不会更新我的数据库

python - 在 Python 中自动读取配置值

Python-从URL、里面的控制和特殊字符获取JSON

Python 3.4 : How to import a module given the full path?

python - 展平可重复树

python - 在 Plotly 气泡图中标记特定气泡

python - 如何解决 Python 3.6 中的 UnicodeDecodeError?

python - 什么是 <class 'range' >

python - 如何获得 pandas 系列中最接近零值的 n 个值?

python - 将图像数据从 python 传递到 c++ 中的 cv::mat