Python:如何在一行中检查字符串中出现的字符

标签 python

一个字符串的末尾可以同时带有单'_' 和双'__' 下划线字符。 检查它:

if myString[-1]=='_': pass

仅适用于单个字符。如何使用一条线实现相同的目标?

(仅当最后一个字符 =='_' 或 '__' 时)。

最佳答案

对于 Python 版本 > 2.5,

您可以使用 endswith with a tuple

underscores = ('_', '__')
if myString.endswith(underscores): pass

演示

>>> underscores = ('_', '__')
>>> xx = "text__"
>>> xxx = "text_"
>>> xx.endswith(underscores)
True
>>> xxx.endswith(underscores)
True
>>> 

关于Python:如何在一行中检查字符串中出现的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23178417/

相关文章:

python - 检测和比较两个图像之间的形状

python - 使用 callable(x) 与 hasattr(x, "__call__")

python - pyfpdf write_html 内联 CSS 样式属性在 fpdf python 中不起作用

python - TensorFlow 2.0 : display progress bar in custom training loop

python - 使用 python 解析多行 whatsapp 文本不起作用

python - 有没有办法将新位置添加到 nltk 查找 wordnet 语料库的位置列表中?

python - 获取 xpath() 以返回空值

python - 在 joblib `matlab` 上下文中腌制 `Parallel` 对象时出错

python - 在 Python 中的 OpenCV 3 下合并 HSV channel

python - 访问数组中的元素