Reputation: 23
This currently works for what I'm trying to do (where 'i' is the number I'm checking to see if it is in the 'digit'):
if str(digit) in str(i):
count += 1
However, when I try to use an if comprehension I get an invalid syntax:
count = [count + 1 if str(digit) in str(i)]
I've tried it several different ways using just [count +=1 if...] and count = [count + 1 if...]
Can anyone provide some insight into this issue?
Upvotes: 0
Views: 673
Reputation: 26578
There currently is nothing wrong with the way you are doing it now. Just want to point that out. If you are simply trying to do this in one line, maybe this solution is what you are looking for.
But to answer your comprehension issue:
You have two problems going on here that I'd like to point out.
You should not check if you have a digit in your string by trying to cast it to str
. Simply use isdigit against the character you are checking.
You cannot use a comprehension the way you are trying to use it. What you have to understand about a comprehension, is that you are creating a new list and taking that new list and assigning it to a variable (in your case count
). So doing this:
count = [count + 1....]
Really does not make much sense to do.
What you should do instead if you are looking to do this in a comprehension,
Iterate over each character in a
, for each character, check if it is a digit:
[c.isdigit() for c in a]
Now, with that above part done. You will have a list of 1s for all digits in your word. The next step is to sum
everything together. Now, the extra bit of information to pay attention to, is that when calling sum
on this, we will lose the square brackets, because we will instead use what is called a generator expression.
So, with all that said and done. Your final solution is:
a = "fjf7jjjf77773jf3j"
print(sum(c.isdigit() for c in a))
# outputs 7
Upvotes: 3
Reputation: 103764
You can just sum the boolean value from character.isdigit()
where character is each character in the string.
Consider:
>>> s='abc123def456'
>>> [c.isdigit() for c in s]
[False, False, False, True, True, True, False, False, False, True, True, True]
>>> sum(c.isdigit() for c in s)
6
Upvotes: 1
Reputation: 3626
List comprehension (with square brackets) is used to generate list. But, in your case, you are not really generating any list. However, if you are trying to write an inline if, try -
count = count + 1 if str(digit) in str(i) else count
Upvotes: 1
Reputation: 532
I'm not sure why you would want to get a list in this case because in your first example, you simply incremented an integer variable called count
. If you're looking for something more nuanced, you could try using a function like this:
def count_letter_instance(string="", letter=""):
return sum([1 for x in string if x == letter])
print(count_letter_instance("hello hello hello", "h"))
print(count_letter_instance("cat cat cat", "c"))
Output:
3
3
Upvotes: 0