如何在循环字符串中设置只接受只有两次 '_' 的条件。
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/