Domanda

I have a question. If I have a string, for example:

str1 = 'Wazzup1'

and numbers:

nums = '1234567890'

I need a code that will look into str1 and tell me if it has any number(not all of them). Please help.

È stato utile?

Soluzione 2

Use the any function, which returns a Boolean which is true iff at least one of the elements in the iterable is true.

string = 'Wazzup1'
result = any(c.isdigit() for c in string)
print(result) # True

Altri suggerimenti

Use any and a generator expression:

any(x in nums for x in str1)

Below is a demonstration:

>>> str1 = 'Wazzup1'
>>> nums = '1234567890'
>>> any(x in nums for x in str1)
True
>>>

Note that the above is for when you have a custom set of numbers to test for. However, if you are just looking for digits, then a cleaner approach would be to use str.isdigit:

>>> str1 = 'Wazzup1'
>>> any(x.isdigit() for x in str1)
True
>>>

As most Python programmers will tell you, the most concise way to do this is using:

any(x in nums for x in str1)

However, if you're new to Python or need a better grasp of the basics of string manipulation, then you should learn how to do this using more fundamental tools.

You can access the individual elements of a string, list, tuple, or any other iterable in Python using square brackets around an index. The characters of a string are indexed starting from 0 (e.g. "hello"[0] gives "h").

Using a for loop, the solution is easier to understand for a Python newbie than the above-mentioned any solution:

result = False
for i in range(len(str1)):
    if str1[i] in nums:
        result = True

A Python for loop can also iterate directly over the elements of the string:

result = False
for x in str1:
    if x in nums:
        result = True

In the first code snippet in this post, the expression x in nums for x in str1 uses Python's list comprehension feature. This goes through every element x of str1 and finds the result of x in nums. any(x in nums for x in str1) returns True if (and only if) at least one of these results is True (meaning a numerical digit is in str1). This is much like the second for loop example given in this post, and many Python programmers choose this option because it is concise and still understandable by other Python programmers.

You can use any() and string.digits to check whether the string contain a digit:

import string

if any(x in string.digits for x in str1):
    pass

You could also use a regular expression:

>>> str1 = 'Wazzup1'
>>> import re
>>> bool(re.search(r'\d', str1))
True

Note: there might be a difference in how c.isdigit(), c in nums, int(c) and \d define what is a digit due to locale or Unicode.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top