1

My question is, in all of the walrus examples, they use the whole object for the boolean, e.g.

if (x := len(s)) > 5:
    print(x)

converts

x = len(s)
if x > 5:
    print(x)

Is there a way to do it for slices of x, if x were a string? e.g. x[-1] != ','

Here is code I am looking to convert to walrus operator

title = book.find(class_='title').get_text()
if title[-1:] == '\n':
    title = title[:-1]
stackz
  • 54
  • 6

1 Answers1

0

If this is an example to illustrate the general question, I can't think of a way to incorporate a walrus operator in that situation. However, in this particular case you could one line it with:

title = book.find(class_='title').get_text().rstrip('\n')

which removes all newline characters at the end only if they exist.

Of course, this wouldn't work with more complicated slicing, but if that's the case, keeping the variable definition on a different line might be more readable anyway.

user128029
  • 53
  • 6