Python Program to get a number num and check whether num is three digit number or not?.
Sample Input 1:
1000
Sample Output 1:
Not a three digit number
Sample Input 2:
987
Sample Output 2:
Three digit number
Flow Chart Design
Program or Solution
num1=int[input["Enter your number:"]]
if[num1 < 1000 and num1 > 99]:
print["{} is a 3 digit number ".format[num1]]
else:
print["{} is not a 3 digit number".format[num1]]
Program Explanation
Get input num from user using input[] method check whether the num is greater than 99 and less than 100 using if statement.
if it is true, then print num is three digit number using print[] method.
Else print num is not three digit number using print[] method.
I have a long text line with a lot of random words and numbers, i wish to assign a variable to the only 3 digit number in the line.
The number changes every different line but it is always only 3 digits. How does one search for the only 3 digit number in a linepython? There may be some 3 letter words so it must just be the number.
09824747 18 n 02 archer 0 bowman 0 003 @ 09640897 n 0000
in this example i want the variable digits = 003
asked Jun 12, 2013 at 13:54
JohnConneelyJohnConneely
1,3334 gold badges16 silver badges29 bronze badges
A regular expression with \b
word boundaries would do the trick:
re.findall[r'\b\d{3}\b', inputtext]
returns a list of all 3-digit numbers.
Demo:
>>> import re
>>> inputtext = '09824747 18 n 02 archer 0 bowman 0 003 @ 09640897 n 0000'
>>> re.findall[r'\b\d{3}\b', inputtext]
['003']
>>> inputtext = 'exact: 444, short: 12, long: 1234, at the end of the line: 456'
>>> re.findall[r'\b\d{3}\b', inputtext]
['444', '456']
answered Jun 12, 2013 at 13:58
Martijn Pieters♦Martijn Pieters
986k274 gold badges3881 silver badges3238 bronze badges
You can use regular expressions. Or look for a digit, then check the next two characters manually.
I would use a regexp:
import re
threedig = re.compile[r'\b[\d{3}]\b'] # Regular expression matching three digits.
The \b
means "word boundary", and [\d{3}]
means "three digits", the parenthesis makes it a "group" so the matching text can be found.
Then search using:
mo = threedig.search["09824747 18 n 02 archer 0 bowman 0 003 @ 09640897 n 0000"]
if mo:
print mo.group[1]
The above prints 333
.
answered Jun 12, 2013 at 13:56
2
A solution thanks to regular expressions:
>>> s = "007 09824747 18 n 02 archer 0 bowman 0 003 @ 09640897 n 0000 008"
>>> r = re.findall[r'[?:[^\d]|\A][\d{3}][?:[^\d]|\Z]', s]
>>> r
['007', '003', '008']
answered Jun 12, 2013 at 14:01
EmmanuelEmmanuel
13.5k11 gold badges48 silver badges72 bronze badges
In Python, I got the following to work [based on the answers above]:
re.compile['prefix\d{1,3}\suffix']}]
This covers the scenario for anywhere between 1-3 digits
answered Apr 30, 2018 at 17:15
raTMraTM
3691 gold badge3 silver badges16 bronze badges