⊗pyPmBsNCG 34 of 208 menu

Getting Characters from a Number in Python

Let's consider the case where we want to add up all the digits of some number. If we access them by index as in a string, we get an error:

num = 123 print(num[0] + num[1]) # will display an error

To avoid the error, you must first convert the numbers to strings. Then convert the string character we need back to a numeric type:

txt = '123' print(txt[0] + txt[1]) # '12' - sums as rows

As you can see, the characters in 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 in the string:

num = 123 txt1 = str(num)[0] txt2 = str(num)[1] res = int(txt1) + int(txt2) print(res) # 3

Given a number:

tst = 123

Find the sum of the digits of this number.

Given a number:

tst = 4567

Add the first two digits together. Then subtract the last digit of the number 4567 from the result.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline