4
A
回答
9
是的,你可以用count
方法字符串容易得到一个行的解决方案:
>>> # I named it 'mystr' because it is a bad practice to name a variable 'str'
>>> # Doing so overrides the built-in
>>> mystr = "Hello! My name is Barney!"
>>> mystr.count("!")
2
>>> if mystr.count("!") == 2:
... print True
...
True
>>>
>>> # Just to explain further
>>> help(str.count)
Help on method_descriptor:
count(...)
S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are
interpreted as in slice notation.
>>>
3
1
还有一堆的一个衬垫的方法来找到字符串中的字符数:
string = "Hello! My name is Barney!"
方式:
string.count('!') == 2 #best way
或
len([x for x in string if x == '!']) == 2 #len of compresion with if
或
len(string)-len(string.replace('!','')) == 2 #len of string - len of string w/o character
或
string[string.find('!')+1:].find('!')>0 #find it, and find it again, at least twice
count
是最好的,但我喜欢另想办法,因为我有时会发现冗余代码/变量的方式,这取决于你正在做的,当然什么。假如你已经有了字符串的len和字符串的len,并且在变量中替换了字符,出于某种其他原因,那么你可以简单地减去这些变量。可能不是这种情况,但需要考虑。
0
使用
str.count("!")
所以:
if str.count("!") == 2:
return True
0
相关问题
- 1. 检查字符串是否包含两次相同的字符
- 2. 检查2个字符串是否包含相同的字符?
- 3. 检查两个字符串是否包含相同的模式
- 4. 如何检查一个字符串是否包含两个相同的字符?
- 5. 检查一对字符串是否包含相同的字符?
- 6. 如何检查两个字符串是否包含相同的字母?
- 7. 检查字符串是否包含字(不是子字符串!)
- 8. Applescript:检查一个字符串是否包含空字符串?
- 9. 字符串池是否包含两个具有相同值的字符串?
- 10. 检查字符串是否包含字符集中的字符
- 11. Ruby检查一个字符串是否包含多个不同的字符串?
- 12. Should.js:检查两个数组包含相同字符串
- 13. 检查字符串是否包含除
- 14. 检查是否字符串包含“HTTP://”
- 15. 检查Enum是否包含字符串?
- 16. 检查NSMutableArray是否包含字符串
- 17. 检查行是否包含字符串
- 18. 检查是否WCHAR包含字符串
- 19. Java:检查字符串是否包含多个字符
- 20. 如何检查字符串是否包含某个字符?
- 21. 检查一个字符串是否只包含特殊字符
- 22. 检查一个字符串是否包含给定字符
- 23. 检查一个字符串是否包含任何字符
- 24. Javascript检查字符串是否只包含某个字符
- 25. 检查一个字符串是否包含特定字符
- 26. 检查一个字符串是否只包含某些字符
- 27. 如何检查一个字符串是否多次包含相同的字母?
- 28. 当字符串包含标点符号时检查字符串是否相等
- 29. 如何检查一个字符串是否包含两个星号字符?
- 30. 如何检查VIM中是否没有两行包含相同的字符串
和稍微更耐人寻味的变化会如果有任何一倍字符来快速检查... – beroe