[英]Count number of letters in string (not characters, only letters)
I've tried looking for an answer but I'm only finding how to count the number of characters.我试过寻找答案,但我只找到如何计算字符数。 I need to know how to count the number of letters within a string.我需要知道如何计算字符串中的字母数。 Also need to know how to count the number of numbers in a string.还需要知道如何计算字符串中数字的数量。
For example:例如:
"abc 12"
the output would be输出将是
letters: 3 numbers: 2字母:3 数字:2
You have string methods for both cases.两种情况都有字符串方法。 You can find out more on string — Common string operations您可以了解有关字符串的更多信息— 常见字符串操作
s = "abc 12"
sum(map(str.isalpha, s))
# 3
sum(map(str.isnumeric, s))
# 2
Or using a generator comprehension with sum
:或者使用带有sum
的生成器理解:
sum(i.isalpha() for i in s)
# 3
sum(i.isnumeric() for i in s)
# 2
Something like:就像是:
s = 'abc 123'
len([c for c in s if c.isalpha()])
3
would work.会工作。
Also, since you True
evaluates as 1 and False
as 0, you can do:此外,由于您的True
评估为 1 且False
评估为 0,您可以执行以下操作:
sum(c.isalpha() for c in s)
You can use string.isdigit()
which checks if a string(or character) contains only digits and string.isalpha()
which checks if a string(or character) contains only characters and do this您可以使用string.isdigit()
检查字符串(或字符)是否仅包含数字和string.isalpha()
检查字符串(或字符)是否仅包含字符并执行此操作
str='abc 123'
nums=len([char for char in str if char.isdigit()])
chars=len([char for char in str if char.isalpha()])
you can try:你可以试试:
s = 'abc 12'
p = [0 if c.isalpha() else 1 if c.isnumeric() else -1 for c in s]
letters, numeric = p.count(0), p.count(1)
print(letters, numeric)
output:输出:
3 2
Asumming you are using Python 3.6+, I think using generator expressions , the sum
function and a f-strings could solve your problem:假设您使用的是 Python 3.6+,我认为使用generator 表达式、 sum
函数和 f-strings 可以解决您的问题:
>>> s = 'abc 12'
>>> numbers = sum(i.isnumeric() for i in s)
>>> letters = sum(i.isalpha() for i in s)
>>> f'letters: {letters} numbers: {numbers}'
'letters: 3 numbers: 2'
You can do that using lambda function with one line of code :)您可以通过一行代码使用lambda函数来做到这一点:)
counter = lambda word,TYPE: len([l for l in word if l.isalpha()]) if TYPE == str else len([n for n in word if n.isdigit()]) if TYPE == int else len([c for c in word if c.strip()]) if TYPE == all else TypeError("expected 'str' or 'int' or 'all' of 'TYPE' argument")
word = "abcd 123"
lettersCounter = counter(word, str) # >= 4
numbersCounter = counter(word, int) # >= 3
allCounter = counter(word, all) # >= 7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.