How To Check If A String Ends With A Number In Python

String manipulation is a common task in programming, and it often involves checking if a string contains certain characters, words, or numbers.

In Python, you can easily check if a string ends with a number using built-in functions. In this tutorial, we will explore the steps required to check if a string ends with a number in Python.

Steps

1. First, you need to define a string variable that we will use to perform the check. Let’s define a variable called “my_string” and set its value to “Hello123”.

2. Once you have set the string, you can then use the “isdigit()” method to check if the last character in the string is a number. This method returns “True” if the last character in the string is a number, and “False” if it is not.

3. To implement this, use the following code:

This code defines the “my_string” variable, and then checks if the last character in the string is a number using the “isdigit()” method. We then use an “if” statement to check whether the method returns “True” or “False”, and print out a statement accordingly.

4. You can also use regular expressions, which are a powerful tool for pattern matching in Python. To use regular expressions to check if a string ends with a number, you need to import the “re” module, which provides support for regular expressions in Python.

5. Here’s an example code that uses regular expressions to check if a string ends with a number:

In this code, we import the “re” module and then define the “my_string” variable. We then use the “search()” method from the “re” module to search the string “my_string” for a regular expression that matches any digit (“\d”) that occurs at the end of the string (“$”). If the regular expression matches, “search()” returns a match object, and we print out a statement that says the string ends with a number.

If the regular expression doesn’t match, “search()” returns “None”, and we print out a statement that says the string does not end with a number.

Full code:

Output:

String ends with a number
String ends with a number

Conclusion

In this tutorial, we have explored two different methods for checking if a string ends with a number in Python. The first method uses the built-in “isdigit()” method, while the second method uses regular expressions.

Depending on your specific use case, you may find one method more useful than the other. Regardless of which method you choose, both are effective ways to perform this common string manipulation task.