Python Whitespace Removal with next() and enumerate()

How to use #Python's `next()` method and `enumerate()` to determine how much whitespace there is at the beginning and the end of a string. Yes, this is over-engineered and silly code 🐍🤡

  • No alternative text description for this image

Don't forget to guard against the case where no item is found ! If an iterator reaches its end, it raises `StopIteration`. So you can catch that. Or, you can use the "extended" syntax of `next`, which can take as an argument what should be returned if `StopIteration` is raised: next((x for x in it), "default"). You can use `None` as the default return and check for None, but it's not as pythonic as catching `StopIteration`.

Like
Reply

print(len(s) - len(s.strip())) Do not overoptimize and overcomplicate

Like
Reply

Clever use of concepts!

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories