Python counts the number of numbers in a string

Release: 2020-01-15 13:39:39
Original
30699 people have browsed it

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
Copy after login

Input string

a = input(‘please input a str\n’)
Copy after login

Traverse the string to count the number of digits:

for i in a:
# 判断是否为数字
if i.isdigit():
int_count += 1

print(‘数字 = %d, ’ %( int_count ))
Copy after login

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

Syntax

isdigit() method syntax:

str.isdigit()
Copy after login

Return value

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

python learning network, free online learning python 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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template