In my test code, I want to assert that a string ends with a number. Say the number is between [0,3):
assert_equals('/api_vod_asset/v0/assets/0', '/api_vod_asset/v0/assets/number') #valid
assert_equals('/api_vod_asset/v0/assets/1', '/api_vod_asset/v0/assets/number') #valid
assert_equals('/api_vod_asset/v0/assets/5', '/api_vod_asset/v0/assets/number') #invalid
How to use regular expression or some other technique for number
?
Python String endswith() Method. Python String endswith() method returns True if a string ends with the given suffix, otherwise returns False.
You can check if a number is present or not present in a Python range() object. To check if given number is in a range, use Python if statement with in keyword as shown below. number in range() expression returns a boolean value: True if number is present in the range(), False if number is not present in the range.
Use string. endswith() to check if a string ends with any string from a list. Call str. endswith(suffix) to check if str ends with suffix .
We can use the isdigit() function to check if the string is an integer or not in Python. The isdigit() method returns True if all characters in a string are digits. Otherwise, it returns False.
You would probably want to use assertRegex:
test_case.assertRegex('/api_vod_asset/v0/assets/0', '/api_vod_asset/v0/assets/[012]')
The one above works in the case of [0,3) range. If you do not want that restriction, you would likely want to have:
test_case.assertRegex('/api_vod_asset/v0/assets/0', '/api_vod_asset/v0/assets/[\d]')
All the code above works after the following lines have been added to your snippet:
import unittest as ut
test_case = ut.TestCase()
If it will always be at the same place in the string, you can use string.split
something like
def check_range(to_test, valid_range):
return int(to_test.split('/')[-1]) in range(valid_range[0], valid_range[1] + 1)
then you can do
check_range('/api_vod_asset/v0/assets/0', [0,3]) #True
check_range('/api_vod_asset/v0/assets/1', [0,3]) #True
check_range('/api_vod_asset/v0/assets/5', [0,3]) #False
First, use a regex like \d+$
to get any number (\d+
) at the end of the string ($
)...
>>> m = re.search(r"\d+$", s)
... then check whether you have a match and whether the number is in the required range:
>>> m is not None and 0 <= int(m.group()) < 3
Or use a range
, if you prefer this notation (assuming upper bound of [0,3)
is exclusive):
>>> m is not None and int(m.group()) in range(0, 3)
I want to assert that a string ends with a number
if int(myString[-1]) in [0,1,2]:
do something...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With