w3resource

Python: Where a string will start with a specific number


15. Starts with Specific Number

Write a Python program that starts each string with a specific number.

Sample Solution:

Python Code:

import re
def match_num(string):
    text = re.compile(r"^5")
    if text.match(string):
        return True
    else:
        return False
print(match_num('5-2345861'))
print(match_num('6-2345861'))

Sample Output:

True                                                                                                          
False

Pictorial Presentation:

Python: Regular Expression - Where a string will start with a specific number.
Python: Regular Expression - Where a string will start with a specific number.

Flowchart:

Flowchart: Regular Expression - Where a string will start with a specific number.

For more Practice: Solve these Related Problems:

  • Write a Python program to verify that each string in a list starts with a given number and then print the valid strings.
  • Write a Python script to filter a list of strings to only those that begin with the digit '5'.
  • Write a Python program to check if a string starts with a specific number and then extract that number for further processing.
  • Write a Python program to match strings that start with a particular digit and then follow a specific pattern using regex.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to match a string that contains only upper and lowercase letters, numbers, and underscores.
Next: Write a Python program to remove leading zeros from an IP address.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.