Python Forum

Full Version: String formatting issues?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
#I created a program with two functions and a variable as follows:

def isHarshad(num):
    if num % sum([int(x) for x in list(str(num))]) == 0:
        return True
    else:
        return False
    

def isSiete(num):
    String = str(num)
    Tens = len(str(num)) - 2

    if String[Tens] == '7':
        return True
    else:
        return False

Hodges = 14
#Afterwards, I opened up a new program , imported the functions and opened a file (5000 random numbers) and was trying to read the file using the functions I made and imported:

from myLib import isHarshad, isSiete, Hodges

f = open('Rumbers.txt', 'r')
data = f.read()

f.close()

for i in data:
    if isHarshad(i) == True:
        print(i)


#However, running this gives me an error:

Error:
File "/Users/Name/Desktop/Python/myLib.py", line 6, in isHarshad if num % sum([int(x) for x in list(str(num))]) == 0: TypeError: not all arguments converted during string formatting
#I'm a little stuck here and can't move forward - did I mess up the formatting by keeping the first function in a string when the data I'm trying to read is integers?


Any help would be appreciated! Thank You guys so much!
There are multiple issues in your code that lead to that error.

  1. When you read the file like data = f.read(), the whole file is stored in data as one big string
  2. When you iterate over data for i in data: the name i will take one char at a time (again string), e.g. if on first line you have 1234 (note that is part of one big string - the file content), the value of i will be '1' (note that is a string).
  3. When you pass it as argument to your function num is a string. And % is used also as so called old-style string formatting (look at https://pyformat.info/). So, because num is a string it try to apply string formatting, not modulo operator. Because it cannot do that (there are no placeholders in num)- you get the error.

You should know that latest tool for string formatting are f-strings, they are not represented in the link I shared.
Also, because mum is a string, you don't have to do str(num).
May or may not be a problem, but you are converting the same thing into a list, and string, and a integer all in the same line.

Moreover, num is going to be a string when you read it from the file anyway. It wouldn't hurt to convert num into a list of integers first, then plug it into the list comprehension... I'm guessing.

EDIT: but it looks like you got a better, proper answer posted already, so, listen to that. lol