计数字符串参数

2024-04-25 12:18:21 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有一个内置函数,或者一个好方法来计算字符串中的参数数量。例如:

"Here is my {}, and it has a {}"

我希望能够确定该字符串中的参数数是2,因此我可以将该值用于循环以获取用户的输入。你知道吗


Tags: and方法函数字符串用户参数数量here
2条回答

根据你想要达到的目标,可能会有更优雅的解决方案。你知道吗

要回答您的问题,^{} class可以帮助您。
与其他建议的解决方案不同,这个解决方案不依赖于使用regex或字符串搜索的自定义解析,因为它使用python自己的字符串解析器,并且保证是正确的。你知道吗

下面是一个示例代码,返回字符串中的参数数, 它实例化一个新的Formatter对象并对其调用parse方法。根据documentation,它将字符串拆分为一个元组列表,我们需要将那些具有非None值的字符串保留在第二个位置:

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)

我认为你应该用regex来处理这个案子,因为它们很快。你知道吗

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)))

希望有帮助:),祝你好运

相关问题 更多 >

    热门问题