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

时间:2018-01-02 09:50:51

标签: 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。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用此RegEx:

\B%s\b

它只会匹配独立字词(='等符号不计入此内容)并且如果它在新行上,则不会中断, String的一行或一行。 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
相关问题