parse(format_string)
Loop over the format_string and return an iterable of tuples (literal_text, field_name, format_spec, conversion). This is used by vformat() to break the string into either literal text, or replacement fields.
The values in the tuple conceptually represent a span of literal text followed by a single replacement field. If there is no literal text (which can happen if two replacement fields occur consecutively), then literal_text will be a zero-length string. If there is no replacement field, then the values of field_name, format_spec and conversion will be None.
import string
s = "Here is my {}, and it has a {}"
n_params = len( [e for e in list(string.Formatter().parse(s)) if e[1] is not None] )
print(n_params)
import re
string = "Hope it helps you {}. I think this is correct way {}.You are looking for empty braces right {}.Because this code won't count the { filled up ones }."
searched_braces = re.findall(r"{}",string)
print(searched_braces)
print(len(searched_braces))
#it can implemented in one line too.
print(len(re.findall(r"{}",string)))
第二种情况,如果你正在寻找填补了花括号太
import re
string = "Hope it helps you {}. I think this is correct way {}.If you are not looking for empty braces only{}. Because this code counts the { filled up ones too }."
searched_braces = re.findall(r"{.*?}",string)
print(searched_braces)
print(len(searched_braces))
#it can implemented in one line too.
print(len(re.findall(r"{.*?}",string)))
根据你想要达到的目标,可能会有更优雅的解决方案。你知道吗
要回答您的问题,^{} class 可以帮助您。
与其他建议的解决方案不同,这个解决方案不依赖于使用regex或字符串搜索的自定义解析,因为它使用python自己的字符串解析器,并且保证是正确的。你知道吗
下面是一个示例代码,返回字符串中的参数数, 它实例化一个新的
Formatter
对象并对其调用parse
方法。根据documentation,它将字符串拆分为一个元组列表,我们需要将那些具有非None值的字符串保留在第二个位置:我认为你应该用regex来处理这个案子,因为它们很快。你知道吗
第二种情况,如果你正在寻找填补了花括号太
希望有帮助:),祝你好运
相关问题 更多 >
编程相关推荐