Home>Article>Backend Development> Python counts the number of numbers in a string

Python counts the number of numbers in a string

尚
Original
2020-01-15 13:39:39 30590browse

Python counts the number of numbers in a string

Python’s method of counting the number of numbers in a string:

① Define the initial number of numbers, letters and other types of characters to be 0

② Traverse the string, determine the type of each character in the string, and accumulate them respectively

③Output results

Implementation code:

Initial number of numbers

int_count = 0

Input string

a = input(‘please input a str\n’)

Traverse the string to count the number of digits:

for i in a: # 判断是否为数字 if i.isdigit(): int_count += 1 print(‘数字 = %d, ’ %( int_count ))

Python isdigit() method detects whether the string consists only of digits.

Syntax

isdigit() method syntax:

str.isdigit()

Return value

Returns True if the string contains only digits, otherwise returns False.

python learning network, free online learningpython platform, welcome to pay attention!

The above is the detailed content of Python counts the number of numbers in a string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn