p ython英文字符统计
时间: 2023-07-11 10:40:06 浏览: 46
Sure! Here's a Python code to count the number of English characters in a string:
```python
def count_english_characters(string):
count = 0
for char in string:
if char.isalpha() and char.isascii():
count += 1
return count
```
You can call this function with a string as an argument to count the number of English characters in it. For example:
```python
my_string = "Hello, World! 你好,世界!"
english_count = count_english_characters(my_string)
print("Number of English characters:", english_count)
```
This will output:
```
Number of English characters: 13
```
相关问题
p ython统计字符串出现个数
可以使用Python中的Counter模块来统计字符串中每个字符出现的个数,示例代码如下:
```python
from collections import Counter
s = "hello world"
char_count = Counter(s)
print(char_count)
```
输出结果为:
```
Counter({'l': 3, 'o': 2, 'e': 1, 'h': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
```
其中,Counter返回的是一个字典,键为字符串中的每个字符,值为该字符在字符串中出现的次数。
p ython统计字符串出现的次数
可以使用Python内置函数`count`来统计字符串中某个字符或子串出现的次数。
例如,如果想要统计字符串`"hello world"`中字符`l`出现的次数,可以这样写:
```
s = "hello world"
count = s.count('l')
print(count)
```
输出结果为:
```
3
```
如果想要统计子串`"lo"`出现的次数,可以这样写:
```
s = "hello world"
count = s.count('lo')
print(count)
```
输出结果为:
```
1
```