How do i find the 3 digit number in a string python?

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 PietersMartijn Pieters

987k274 gold badges3881 silver badges3239 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

Format a number to 3 digits in Python #

Use a formatted string literal to format a number to 3 digits, e.g. result = f'{my_int:03d}'. The formatted string literal will format the number to the specified fixed length by adding leading zeros.

Copied!

from random import randint my_int = 5 # ✅ pad number with leading zeros [formatted-string literal] result = f'{my_int:03d}' print[result] # 👉️ '005' # ----------------------------------- # ✅ pad number with leading zeros [zfill] result = str[my_int].zfill[3] print[result] # 👉️ '005' # ---------------------------------- # ✅ get first 3 digits of number result = str[1234567][:3] print[result] # 👉️ 123 # ---------------------------------- # ✅ generate random 3 digit number result = randint[100, 999] print[result] # 👉️ 465 # ---------------------------------- # ✅ generate list of 3 digit numbers my_list = [f'{item:03d}' for item in range[10]] # 👇️ ['000', '001', '002', '003', '004', '005', '006', '007', '008', '009'] print[my_list]

The first example uses a formatted string literal to format a number to 3 digits by adding leading zeros.

Copied!

my_int = 5 result = f'{my_int:03d}' print[result] # 👉️ '005' print[f'{9:03d}'] # 👉️ 009

Formatted string literals [f-strings] let us include expressions inside of a string by prefixing the string with f.

Copied!

my_str = 'The number is:' my_int = 137 result = f'{my_str} {my_int}' print[result] # 👉️ The number is: 137

Make sure to wrap expressions in curly braces - {expression}.

Formatted string literals also enable us to use the format specification mini-language in expression blocks.

Alternatively, you can use the str.zfill[] method.

Format a number to 3 digits using str.zfill[] #

To format a number to 3 digits:

  1. Use the str[] class to convert the number to a string.
  2. Use the str.zfill[] method to format the number to 3 digits.
  3. The str.zfill[] method will format the number to 3 digits by left-filling it with 0 digits.

Copied!

my_int = 5 result = str[my_int].zfill[3] print[result] # 👉️ '005'

The str.zfill method takes the width of the string and left-fills the string with 0 digits to make it of the specified width.

Copied!

num = 13 result_1 = str[num].zfill[3] print[result_1] # 👉️ '013' result_2 = str[num].zfill[4] print[result_2] # 👉️ '0013'

Converting the number 13 to a string gives us a string with a length of 2.

Passing 3 as the width to the zfill[] method means that the string will get left-filled with a single 0 digit.

If you need to get the first 3 digits of an integer, convert the integer to a string and use string slicing.

Copied!

result = str[1234567][:3] print[result] # 👉️ '123' my_int = int[result] print[my_int] # 👉️ 123

The slice goes from index 0 up to, but not including the digit at index 3.

If you need to generate a random 3-digit number, use the randint[] function.

Copied!

from random import randint result = randint[100, 999] print[result] # 👉️ 465

The random.randint function takes 2 numbers - a and b as parameters and returns a random integer in the range.

Note that the range is inclusive - meaning both a and b can be returned.

If you need to generate a list of 3-digit numbers, use a list comprehension.

Copied!

my_list = [f'{item:03d}' for item in range[10]] # 👇️ ['000', '001', '002', '003', '004', '005', '006', '007', '008', '009'] print[my_list]

We used a list comprehension to iterate over a range of numbers.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we use a formatted string literal to pad the current number with leading zeros to a length of 3.

How do you find the 3 digit number in Python?

Format a number to 3 digits using str..
Use the str[] class to convert the number to a string..
Use the str. zfill[] method to format the number to 3 digits..
The str. zfill[] method will format the number to 3 digits by left-filling it with 0 digits..

How do you find the number of digits in a string in Python?

Python String isdigit[] The isdigit[] method returns True if all characters in a string are digits. If not, it returns False .

How do you find a 3 digit number?

3-digit numbers are those numbers that consist of only 3 digits. They start from 100 and go on till 999. For example, 673, 104, 985 are 3-digit numbers. It is to be noted that the first digit of a three-digit number cannot be zero because in that case, it becomes a 2-digit number.

How do I extract a two digit number from a string in Python?

Summary: To extract numbers from a given string in Python you can use one of the following methods:.
Use the regex module..
Use split[] and append[] functions on a list..
Use a List Comprehension with isdigit[] and split[] functions..
Use the num_from_string module..

Chủ Đề