gpt4 book ai didi

python - 检查字符串中的最后一个匹配字符

转载 作者:太空宇宙 更新时间:2023-11-04 10:38:52 25 4
gpt4 key购买 nike

我想查找字符串的最后一个字符是否为 .。我知道在 re 中使用 $ 更容易找到。但是,有没有一种不用re 就能找到. 的简单方法? re 是否也比其他字符串操作模块更快?

string1 = "this is a string1."
string2 = "this is a string2."
string3 = "this is a string3."

字符串总是在最后包含.

最佳答案

使用str.endswith :

>>> string1 = "this is a string1."
>>> string1.endswith('.')
True

>>> string4 = "this is a string1?"
>>> string4.endswith('.')
False

根据 Regular expression HOWTO - Python documentation :

Regular expression patterns are compiled into a series of bytecodes which are then executed by a matching engine written in C. For advanced use, it may be necessary to pay careful attention to how the engine will execute a given RE, and write the RE in a certain way in order to produce bytecode that runs faster.

关于python - 检查字符串中的最后一个匹配字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21970027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com