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...

3
  • 1
    You might want to try defining __repr__ on your class as well as or instead of __str__. Commented Jan 12, 2016 at 13:28
  • 1
    Just so you know, Python already has a Fraction class, so you don't necessarily need to write your own. (also, "fracture" is probably not the word you're looking for) Commented Jan 12, 2016 at 13:29
  • 1
    Possible duplicate of Joining List has integer values with python Commented Jan 12, 2016 at 19:37

4 Answers 4

6

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)))
Sign up to request clarification or add additional context in comments.

Comments

1

You have to convert the ints to strings first:

numbers = (1, 2, 3)
print(' < '.join(str(x) for x in numbers))

Comments

1

You can convert your array using map:

print(' < '.join(map(str,(1,2,3))))

Comments

0

You can convert integers to string.

print(' < '.join((str(1),str(2),str(3))))

3 Comments

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
A code block alone does not provide a good answer. Please add explanations (why it solve the issue, where was the mistake, etc...)
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.