Home > database >  Printing list of strings
Printing list of strings

Time:11-14

I am completely new to python, and am trying to print some elements of my list. In second print() I am getting error, which is: 'list indices must be integers or slices, not str'. The output should be The sum of digits operation performs 1 4. Where am I wrong?

def sum_of_digits(s):
  letters = []
  numbers = []

  for i in s:
    if i.isalpha():
     letters.append(i)
    elif i.isdigit():
      numbers.append(i)
  print("The extracted non-digits are: {} ". format(letters), end="\n")    
  print("The sum of digits operation performs ", s.join(int(i, numbers[i])))

sum_of_digits("1aw4") 

CodePudding user response:

Let's examine s.join(int(i, numbers[i]))

  • int(a,b) mean convert a as an int with base b, for example

    int('11011', 2)  # 27
    int('11011', 8)  # 4617
    int('11011', 10) # 11011
    

    and i in your case is the last char of the string, even numbers[i] is not possible (that's where the exception is)

  • s.join would mean to put the original s string between each value of the given parameter, non-sens too


You may convert to int each char that is a digit, then just use sum

Sum result

def sum_of_digits(s):
    letters = []
    numbers = []
    for i in s:
        if i.isalpha():
            letters.append(i)
        elif i.isdigit():
            numbers.append(int(i))
    print("The extracted non-digits are: {} ".format(letters), end="\n")
    print("The sum of digits operation performs ", sum(numbers))

The extracted non-digits are: ['a', 'w']
The sum of digits operation performs  5

Sum operation

def sum_of_digits(s):
    letters = []
    numbers = []
    for i in s:
        if i.isalpha():
            letters.append(i)
        elif i.isdigit():
            numbers.append(i)
    print("The extracted non-digits are: {} ".format(letters), end="\n")
    print("The sum of digits operation performs ", " ".join(numbers))


The extracted non-digits are: ['a', 'w']
The sum of digits operation performs  1 4

CodePudding user response:

numbers[i] causes that error because i is a string (it's the last character from the for i in s: loop). Since numbers is a list, indexes must be integers, not strings.

The argument to join should just be the list of strings that you want to join. You don't need to call int(), and you don't need to use i.

The join() method should be called on the string that you want to be the delimiter between each of the elements when they're joined. If you just want to concatenate all the elements, use an empty string, not s.

print("The sum of digits operation performs ", "".join(numbers))

This prints:

The sum of digits operation performs  14

DEMO

  • Related