how to count the letters in a string? [duplicate] - python

This question already has answers here:
How to count digits, letters, spaces for a string in Python?
(12 answers)
Closed 5 years ago.
how do I code a program that would produce this below?
As an example, the following code fragment:
print (count_letters("ab1c2d345"))
should produce the output:
4

You can try this:
def count_letters(s):
return len([i for i in s if i.isalpha()])
print(count_letters('ab1c2d345'))
Output:
4
Or, you can use regex for a cleaner solution:
import re
def count_letters(s):
return len(re.findall('[a-zA-Z]', s))

You can do it using simple loop/if statement.
def count_letters(str_ltr):
count_ltr = 0
for ch in str_ltr:
if ch.isalpha():
count_ltr += 1
return count_ltr
print(count_letters("ab1c2d345"))
Output: 4

Related

How to insert a variable in a regex pattern? [duplicate]

This question already has answers here:
How to use a variable inside a regular expression?
(12 answers)
Closed 2 years ago.
i have a list :
cpt=0
list=["dermato","bioderma", "gatoderma"]
for l in list:
if re.findall(".*derma.*",l):
cpt=cpt+1
So, instead of putting directly 'derma' as regex , i want :
a= "derma" #initialize
list=["dermato","bioderma", "gatoderma"]
for l in list:
if re.findall(".*a.*",l):
cpt=cpt+1
You can use an f-string:
a= "derma"
list = ["dermato","bioderma", "gatoderma"]
for l in list:
if re.findall(f".*{a}.*", l):
cpt += 1

Find count of sub_string in string [duplicate]

This question already has answers here:
String count with overlapping occurrences [closed]
(25 answers)
Closed 4 years ago.
Why is this giving output as 1 and not 2:
string = "ABCDCDC"
print(string.count("CDC"))
Also, since this is not working, how can I get 2 in this case?
You could use a regular expression to count overlapping substrings:
import re
string = "ABCDCDC"
print(len(re.findall('(?=CDC)', string))) # 2
Here is an algorithmic solution
string = "ABCDCDC"
sub_string = "CDC"
count = 0
for i in range(len(string)):
if string[i:len(sub_string)+i] == sub_string:
count += 1
print count
import re
print([m.start() for m in re.finditer('(?=CDC)', 'ABCDCDC')])
This should find all potentially overlapping occurences
You can try this simple way:
def overlapping_count(string, seek):
seek_len = len(seek)
return sum(c == seek[0] and string[i:i + seek_len] == seek
for i, c in enumerate(string))
string = "ABCDCDC"
print(overlapping_count(string, "CDC"))

How to count the number of a specific character at the end of a string ignoring duplicates? [duplicate]

This question already has answers here:
Pythonic way to count the number of trailing zeros in base 2
(5 answers)
Closed 5 years ago.
I have a series of strings like:
my_text = "one? two three??"
I want to count only the number of ? at the end of the string. The above should return 2 (rather than 3).
What I've tried so far:
my_text.count("?") # returns 3
There's not a built-in method for it. But something simple like this should do the trick:
>>> len(my_text) - len(my_text.rstrip('?'))
2
You could also use a regexp to count the number of trailing question marks :
import re
def count_trailing_question_marks(text):
last_question_marks = re.compile("\?*$")
return len(last_question_marks.search(text).group(0))
print count_trailing_question_marks("one? two three??")
# 2
print count_trailing_question_marks("one? two three")
# 0
Not so clean but simple way:
my_text = "one? two three??"
total = 0
question_mark = '?'
i = 0
for c in my_text:
i -= 1
if my_text[i] == question_mark:
total += 1
else:
break
One-liner using my favourite itertools:
First reverse the string, then continue iterating (taking the values) while our condition is satisfied (value == '?'). This returns an iterable which we exhaust into a list and finally take its length.
len(list(itertools.takewhile(lambda x:x=='?',reversed(my_text))))

Split a string's digits every 3rd digit [duplicate]

This question already has answers here:
Add 'decimal-mark' thousands separators to a number
(9 answers)
Closed 6 years ago.
I have this string
s = '4294967296'
I want to split this into
4.294.967.296
Basically I want to insert a dot every 3rd digit. How can I do this? I tried
c = '4294967296'
for x,y in enumerate(c[::-1]):
if x % 2 == 0:
b = c[:x] + '.' + c[:x]
print (b)
But the output was
>>>
42949672.42949672
>>>
You can (ab)use string formatting:
s = '4294967296'
t = format(int(s), ',').replace(',', '.')
# '4.294.967.296'

Count of a string in a list [duplicate]

This question already has answers here:
How do I count the occurrences of a list item?
(30 answers)
Closed 9 years ago.
I need help:
I want to write function that: takes a list as a input and return count of specific string.
If function input is x=[a,a,b,c] function need return 2 (a is two times in this list).
>>> def F(seq, string):
return seq.count(string)
>>> F(['a','a','b','c'], 'a')
2
Equivalent to:
def F(seq, string):
n = 0
for x in seq:
if x == string:
n += 1
return n

Categories