Strings with numbers in Python
Let's say we have a string containing only numbers:
txt = '123' # string of numbers
Let's find, for example, the sum of its first and second symbols:
txt = '123'
print(txt[0] + txt[1]) # '12' - sums as rows
As you can see, the characters of our string are also strings and are summed as strings. Let's say we want to sum them as numbers. To do this, we apply the int
function to each character of the string:
txt = '123'
print(int(txt[0]) + int(txt[1])) # 3
Given a string '12345'
. Find the sum of the digits of this string.
Given a string '2489'
. Subtract the second character from the third, then multiply the result by the first character.