python - 如何在 python 中的字符串中找到 %s 的确切出现

标签 python

我有一些 SQL 字符串,我想从中找到字符 %s 出现的次数。

示例字符串:

query_fetch_user = """select * from users where id=%s and email LIKE '%sayhello%' """

在这里,我只想获得 %s 的确切计数,并且我想避免将电子邮件部分计入计数。

我试过的。

query_fetch_user.count("%s")

这算作 2

count = start = 0
while True:
   start = query_fetch_user.find(sub, start) + 1
   if start > 0:
        count+=1
   else:
       print(count)

这也算作 2

但实际计数应该是1。

最佳答案

您可以尝试改用此 RegEx:

\B%s\b

它只会匹配独立的单词(像 =' 这样的符号不计入那个)并且如果它在一个新行上,它不会中断,结束字符串的一行或结尾。 Regex101 .

解释:

\B - Starts where \b does not match - essentially to find where there is a non-word character in front of the text (the start of the line, just after a linebreak, start of the String, period, space, etc)
%s - the String itself (in this case the literal `%s`)
\b - and ends at the word boundary - meaning where the word ends

关于python - 如何在 python 中的字符串中找到 %s 的确切出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48058717/

相关文章:

python - networkx 按属性搜索节点

python - 在 Mac OS Mavericks 10.9.2 上升级 scipy

python - Pandas:合并重复的索引值

python - 扩展 Django Flatpages 以接受模板标签

python - 使用 python 日志记录包,如何将额外的格式插入到具有自己的格式化程序的多个记录器处理程序中?

python - 检查函数是否在 Python 中返回 false

python - 同时下载多个页面?

python - 在 Python 中将字节转换为整数

python - 正则表达式 - `^`、 `$` 和 `\A`、 `\Z` 之间的差异

python - 在 Mac 上将 Python 升级到 2.6