Knowee
Questions
Features
Study Tools

Write a Python program to search the numbers (0-9) of length between 1 to 3 in a given string

Question

Write a Python program to search the numbers (0-9) of length between 1 to 3 in a given string

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a Python program that uses regular expressions to find numbers of length 1 to 3 in a given string:

import re

def find_numbers_in_string(string):
    pattern = r'\b\d{1,3}\b'
    result = re.findall(pattern, string)
    return result

# Test the function
string = "123 abc456 7890 abc 12"
print(find_numbers_in_string(string))

In this program, we first import the re module, which allows us to use regular expressions. We then define a function find_numbers_in_string that takes a string as input.

Inside the function, we define a pattern to search for. The pattern \b\d{1,3}\b means "find sequences of digits (\d) of length 1 to 3 ({1,3}) that are whole words (\b on both sides)".

We then use re.findall to find all matches of the pattern in the string. The function returns a list of all matches.

Finally, we test the function with a string that contains numbers of various lengths. The function should return a list of the numbers of length 1 to 3.

This problem has been solved

Similar Questions

Python program that accepts a string and calculate the number of digits and letters and space

Python code to calculate the number of digits in a string.Sample Input:Welc0meSample OutputThe number of digits is: 1

Write a program to count number of words in a given string whose length is greater than 3.For example:Input Resultpython is easier than C3

Given a string of positive number ranging from 0 to 9, the task is to check whether the number is valid pin code or not, by using Python Regular Expression.

Give a regular expression for all strings whose length is strictly greater than 3.

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.