'X'
[ ]
Note that the first index in a sequence is always zero
.
Since the first index of a sequence is zero
, the last index is going to be the length of the string minus 1
in
operatorThe in
operator determines whether a given value is a constituent element of a sequence (such as a string)
Print only digits, one at a time.
Write a function count_nondigits
to return the number of characters that are not digits (0-9) in a string.
How to check if a string can be converted to an integer or float?
Can we use the string method.isnumeric()
?
Function name is_numeric
that takes one string
argument of any length (assume length > 0).
It returns True
if every character in the argument is a digit (0-9) or a period (.), False
otherwise.
Use in
operator instead of built-in function isnumeric()
.
is_numeric()
– solutiondef is_numeric(my_string):
index = 0
count_period = 0
while index < len(my_string):
if my_string[index] == ".":
count_period += 1
if my_string[index] not in "0123456789." or count_period > 1:
return False
index += 1
return True
def main():
assert is_numeric("234") == True
assert is_numeric("abc") == False
assert is_numeric("12c") == False
assert is_numeric("12.3") == True
assert is_numeric("1.2.3") == False
main()