Me Myself
Me Myself

Reputation: 3

Extracting individual numbers from string (python)

I have a long code e.g 545362783 and would like to add the consists numbers together and multiply them, like (1*5)+(2*4)+(3*5)+(4*3)+(5*6) etc.

Is there a simple solution to get them as a integer so I could use these in math. Many thanks!

Upvotes: 0

Views: 84

Answers (5)

norok2
norok2

Reputation: 26886

One way of doing it:

s = '545362783'

a = sum(x * int(c) for x, c in zip(range(1, len(s) + 1), s))
print(a)
# 222

What is happening is the following:

  • s is just a string so looping through it will give each char
  • range(1, len(s) + 1) will give integers from 1 until the length of s
  • zip() is grouping its arguments so that 1 and '5' (etc.) are yielded at the same time by the for loop
  • then, c which contains the characters, is converted to int
  • finally all is multiplied together and summed up with sum()

The same could be done a little more efficiently enumerate() (making good use of the start parameter, similarly to what is done in @shahaf's answer):

a = sum(x * int(c) for x, c in enumerate(s, 1))

This is essentially the same as above but a bit more elegant (and probably also faster). The behavior of enumerate() is just to yield an index accompanying the object being looped through.

Upvotes: 2

FObersteiner
FObersteiner

Reputation: 25544

try unpacking

s = '545362783'
# --> to map each character of the string to a list:
print([*s])
['5', '4', '5', '3', '6', '2', '7', '8', '3']

# --> to map each character of the string directly to a list of integers:
# (thanks Mykola Zotko for the comment!)
print(list(map(int, s)))
[5, 4, 5, 3, 6, 2, 7, 8, 3]

more on the unpacking operator * see e.g. here.

Upvotes: 1

indhu
indhu

Reputation: 101

def count_substring(string):
    string = '545362783'
    multi = []
    for i in range(0, len(string)):
       multiplied = int(i+1) * int(string[i])
       multi.append(multiplied) 

print (multi)
print (sum(multi))

You may try this.

Output:

[5, 8, 15, 12, 30, 12, 49, 64, 27]

222

Upvotes: 0

shahaf
shahaf

Reputation: 4973

you can write a fairly simple method to do it, smth like so

num_str = "545362783"
total = 0;
for idx, num in enumerate(num_str, 1):
  total += idx * int(num)

Upvotes: 1

Smack Alpha
Smack Alpha

Reputation: 1980

Here's the Solution. I hope it may help u:

a = list(str(545362783))
count = 1
c = []
for i in a:
    b = count * int(i)
    c.append(b)
    count = count + 1

sum_of_a = sum(c)
print(sum_of_a)

Output:

222

Upvotes: 0

Related Questions