Let's say I have a class like this:
class Cls:
def __init__(self, a,b,c):
self.a = a
self.b = b
self.c = c
def __str__(self):
return f"{self.a} {self.b} {self.c}"
and I want to print only the first two items. I can do this by brute force:
c = Cls(1,2,3)
print(str(c)[:3])
But, is there a more elegant (Pythonic) way to do this?
Your slice only works if the first 2 items are only 1 digit each.
You should split the string into a list using whitespace delimiters and slice that.
c = Cls(12, 345, 6)
print(*str(c).split()[:2])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.