python - 过滤带有符号的字符串出现特定时间

标签 python string

如何在循环字符串中设置只接受只有两次 '_' 的条件。

a = ['q_s_e','s_e_v_e','s_v']# many more like these

在上面的列表中,只有第一个项目应该在循环中使用:

for i in a:
    if '_' in i:
         ...

这需要一切。

怎么做?

最佳答案

您可以使用 count来自字符串的函数:

a = ['q_s_e','s_e_v_e','s_v']
for i in a:
    if i.count('_') == 2:
      print ('hooray')

In simple words, count() method searches the substring in the given string and returns how many times the substring is present in it.

It also takes optional parameters start and end to specify the starting and ending positions in the string respectively.

The syntax of count() method is:

string.count(substring, start=..., end=...)

另一种方法是也过滤开头的字符串数组:

a = ['q_s_e','s_e_v_e','s_v']
for i in filter(lambda k: k.count('_') == 2, a):
    print ('hooray')

关于python - 过滤带有符号的字符串出现特定时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53210301/

相关文章:

python - 在运行时替换 python Mixin 类

python - 在 Django 测试中匹配查询集

python - 如何使用字典为单个键赋予多个值?

java - Java中提取子字符串

python - (如何)我可以在命令行上使用类似于 pdb 的 pydevd 吗?

python - 我无法在 docker 中安装 opencv-contrib-python

C++ linux 套接字在单个调用中将字符串数组(char **)作为连接字符串发送

javascript string.replace(var1, var2)

c - c中的unicode字符串操作

python - 如何在 matplotlib 图形文本中使用(新样式)字符串格式