1

I'm pretty new to python, and I wonder how I can print objects of my class fracture. The str funcion is set properly, I guess

def __str__(self):
    if self._denominator == 1:
        return str(self._numerator)
    else:
        return str(self._numerator)+'/'+str(self._denominator)

because of

>>>print ('%s + %s = %s' % (f1,f2,f1+f2))
1/3 + -1/4 = 1/12 

Now I'd like to print it properly as a sorted array, and I hoped to get something like

>>>print(', '.join(("Sam", "Peter", "James", "Julian", "Ann")))
Sam, Peter, James, Julian, Ann

But this didn't work for my fracture or even for numbers (like print(' < '.join((1,2,3))))

All I got was:

for i in range(len(fractures)):
    if i+1 == len(fractures):
        print (fractures[i])
    else:
        print (fractures[i], end=' < ')

Is this really the best solution? That's quite messing up the code, compared on how easy this works with strings...

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Omega19
  • 13
  • 3
  • 1
    You might want to try defining `__repr__` on your class as well as or instead of `__str__`. – khelwood Jan 12 '16 at 13:28
  • 1
    Just so you know, Python already has a [Fraction](https://docs.python.org/3/library/fractions.html) class, so you don't necessarily need to write your own. (also, "[fracture](https://en.wiktionary.org/wiki/fracture)" is probably not the word you're looking for) – Kevin Jan 12 '16 at 13:29
  • 1
    Possible duplicate of [Joining List has integer values with python](http://stackoverflow.com/questions/3590165/joining-list-has-integer-values-with-python) – GingerPlusPlus Jan 12 '16 at 19:37

4 Answers4

5

If you want to print "1 < 2 < 3" all you need to do is change the type from an int to a string as such:

print(' < '.join(str(n) for n in (1,2,3)))
nico
  • 2,022
  • 4
  • 23
  • 37
1

You have to convert the ints to strings first:

numbers = (1, 2, 3)
print(' < '.join(str(x) for x in numbers))
eumiro
  • 207,213
  • 34
  • 299
  • 261
1

You can convert your array using map:

print(' < '.join(map(str,(1,2,3))))
Valerio
  • 110
  • 4
0

You can convert integers to string.

print(' < '.join((str(1),str(2),str(3))))
tartaruga_casco_mole
  • 1,086
  • 3
  • 21
  • 29
  • 1
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/10865384) – Dennis Kriechel Jan 12 '16 at 14:12
  • A code block alone does not provide a good answer. Please add explanations (why it solve the issue, where was the mistake, etc...) – Louis Barranqueiro Jan 12 '16 at 20:48
  • @DennisKriechel, I think OP was pretty about he knew it **worked** for **string**, but it **didn't work** for int, as you can see an example of his using it himself. The question also stated a possible solution(C style), and I answered **convert integers to string** and block of code. – tartaruga_casco_mole Jan 13 '16 at 00:20