【问题标题】:Check if a string contains substring at the end检查字符串末尾是否包含子字符串
【发布时间】:2014-11-22 07:10:57
【问题描述】:

我想检查一个变量是否在末尾包含一个子字符串。

例如:

text = 'lord_of_pizzas_DFG'

if ???:
    print('You shall pass')
else:
    print('You shall not pass')

我想知道如何检查“DFG”是否在字符串的末尾。我应该写什么而不是 ??? 以使代码打印“你应该通过”?

【问题讨论】:

    标签: python string substring


    【解决方案1】:

    使用str.endswith

    text = 'lord_of_pizzas_DFG'
    
    if text.endswith("DFG"):
        print('You shall pass')
    else:
        print('You shall not pass')
    

    【讨论】:

    • 另外,text[-3:] 如果你想明确地说“最后三个字符”。
    猜你喜欢
    • 2011-11-09
    • 2013-05-18
    • 2013-11-12
    • 2021-12-20
    • 2013-02-05
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 2022-01-02
    相关资源
    最近更新 更多