Last updated: Apr 10, 2024
Reading timeยท6 min
To get the first digit of a number:
str()
class to convert the number to a string.0
.int()
class to convert the result to an integer.num = 246810 first = int(str(num)[0]) print(first) # ๐๏ธ 2
If you need to get the first N digits of a number, click on the following subheading:
We used the str() class to convert the integer to a string so we can access the string at a specific index.
0
, and the last character has an index of -1
or len(my_str) - 1
.The next step is to access the character at index 0
to get the first digit of
the number.
Once we have the first digit, we can use the int() class to convert the string to an integer.
num = 246810 first = int(str(num)[0]) print(first) # ๐๏ธ 2
You can use the same approach if you need to get the first N digits of a number.
num = 246810 first2 = int(str(num)[:2]) print(first2) # ๐๏ธ 24 first3 = int(str(num)[:3]) print(first3) # ๐๏ธ 246
The syntax for string slicing
is my_str[start:stop:step]
.
start
index is inclusive, whereas the stop
index is exclusive (up to, but not including).The slice my_str[:2]
starts at index 0
and goes up to, but not including
index 2
.
Alternatively, you can use recursion.
def get_first_digit(number): if number < 10: return number return get_first_digit(number // 10) print(get_first_digit(2468)) # ๐๏ธ 2 print(get_first_digit(514)) # ๐๏ธ 5 print(get_first_digit(14)) # ๐๏ธ 1 print(get_first_digit(8)) # ๐๏ธ 8
The function checks if the number is less than 10 and if the condition is met, it returns the number.
Otherwise, it returns the result of calling itself with the number floor-divided by 10.
Division /
of integers yields a float, while
floor division //
of integers results
in an integer.
The result of using the floor division operator is that of a mathematical
division with the floor()
function applied to the result.
my_num = 50 print(my_num / 5) # ๐๏ธ 10.0 (float) print(my_num // 5) # ๐๏ธ 10 (int)
We divide the number by 10 until we get a single-digit number and return the result.
To get the first N digits of a number:
str()
class to convert the number to a string.int()
class to convert the result to an integer.number = 13579 # โ Get the first 2 digits of a number first_2 = int(str(number)[:2]) print(first_2) # ๐๏ธ 13 # โ Get the first 3 digits of a number first_3 = int(str(number)[:3]) print(first_3) # ๐๏ธ 135
We used the str()
class to convert the integer to a string so we can use
string slicing.
The first example returns the first two digits of the number.
The slice my_str[:2]
starts at index 0 and goes up to, but not including
index 2.
The syntax for string slicing is my_str[start:stop:step]
.
The start
index is inclusive, whereas the stop
index is exclusive (up to,
but not including).
0
, and the last character has an index of -1
or len(my_str) - 1
.Once we have the first 2 digits, we use the int()
class to convert the string
to an integer.
number = 13579 first_2 = int(str(number)[:2]) print(first_2) # ๐๏ธ 13
Alternatively, you can use recursion.
def get_first_two_digits(number): if number < 100: return number return get_first_two_digits(number // 10) print(get_first_two_digits(2468)) # ๐๏ธ 24 print(get_first_two_digits(514)) # ๐๏ธ 51 print(get_first_two_digits(95)) # ๐๏ธ 95 print(get_first_two_digits(7)) # ๐๏ธ 7
The function checks if the number is less than 100 and if the condition is met, it returns the number.
Otherwise, it returns the result of calling itself with the number floor-divided by 10.
/
of integers yields a float, while floor division //
of integers results in an integer.The result of using the floor division operator is that of a mathematical
division with the floor()
function applied to the result.
my_num = 50 print(my_num / 5) # ๐๏ธ 10.0 (float) print(my_num // 5) # ๐๏ธ 10 (int)
We divide the number by 10 until we get a 2-digit number and return the result.
If you need to get the first three digits of the number, you would check if the
number is less than 1000
.
def get_first_three_digits(number): if number < 1000: return number return get_first_three_digits(number // 10) print(get_first_three_digits(2468)) # ๐๏ธ 246 print(get_first_three_digits(51410)) # ๐๏ธ 514 print(get_first_three_digits(95799)) # ๐๏ธ 957 print(get_first_three_digits(719292)) # ๐๏ธ 719
If you need to get only the first number in a string, use re.search()
.
import re my_str = 'bobby12hadz34.com' match = re.search(r'\d+', my_str) if match: # ๐๏ธ First number found: 12 print('First number found:', match.group()) # ๐๏ธ Index of first digit: 5 print('Index of first digit:', match.start()) else: print('The string does NOT contain any numbers')
The re.search() method looks for the first location in the string where the provided regular expression produces a match.
re.search()
method finds a match, it will return a match
object, otherwise None
is returned.The first argument we passed to the re.search()
method is a regular
expression.
The \d
character matches the digits [0-9]
(and many other digit characters).
The +
matches the preceding character (a digit) 1 or more times.
You can use the start()
method on the match object to get the index of the
first digit in the string.
If you ever need help reading or writing a regular expression, consult the regular expression syntax subheading in the official docs.
The page contains a list of all of the special characters with many useful examples.
We used the match.group()
method to get the entire match.
if
statement before calling the match.group()
method. The re.search()
method would return None
if the string doesn't contain any numbers.You can also use a range of digits [0-9]
if you find the regular expression
more readable.
import re my_str = 'bobby12hadz34.com' match = re.search(r'[0-9]+', my_str) if match: # ๐๏ธ First number found: 12 print('First number found:', match.group()) else: print('The string does NOT contain any numbers')
The square brackets []
are used to indicate a set of characters.
The 0-9
characters match the digits in the range.
To find the index of the first digit in a string:
for
loop to iterate over the string with enumerate()
.str.isdigit()
method to check if each character is a digit.break
statement to break out of the loop.my_str = 'bobby123hadz' for index, char in enumerate(my_str): if char.isdigit(): print(index, char) # ๐๏ธ 5, 1 break
We used the enumerate()
function to get access to the index of the current
iteration.
The enumerate() function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.
my_str = 'bobby' for index, char in enumerate(my_str): print(char, index) # ๐๏ธ b 0, o 1, b 2, b 3, y 4
str.isdigit()
method to check if the current character is a digit.The str.isdigit() method returns
True
if all characters in the string are digits and there is at least 1
character, otherwise False
is returned.
print('A'.isdigit()) # ๐๏ธ False print('5'.isdigit()) # ๐๏ธ True
Once we find a digit, we use the break
statement to break out of the loop.
my_str = 'bobby123hadz' for index, char in enumerate(my_str): if char.isdigit(): print(index, char) # ๐๏ธ 5, 1 break
The break statement breaks out of the
innermost enclosing for
or while
loop.
You can learn more about the related topics by checking out the following tutorials: