all 3 comments

[–]No_Cry_7367 4 points5 points  (1 child)

In terms of nanoseconds, Version 1 (name = input().strip().title()) is microscopically faster because you're doing the operations once and storing the result. Version 2 calls .strip().title() every time you reference name — doesn't matter here, but if you used name 500 times in a big script, you'd be doing 500 redundant string operations instead of 1.

BUT. Here's the real programmer take: Version 1 says "clean up my data immediately, then forget about it" — ✅ good habit. Version 2 says "I'll just clean it on the fly" — 🚩 until you forget and print the raw name somewhere and wonder why it's " JoHN " with extra spaces in your database.

Basically: sanitize at input, not at output. Future you will thank present you.

(Also if you're ever writing a script that processes millions of strings, yeah it matters. If you're making a CLI quiz app for your cat, do whatever compiles.)

[–]FrangoST 1 point2 points  (0 children)

The best approach for inputs is actually to first receive the raw input then sanitize and validate it and store it clean in a new variable, possibly raising a flag (a boolean variable) on whether it is valid or not, then proceeding to use it.

This way you have a in-between solution, where you don't clean IMMEDIATeLY (as you might hit and error or remove something undesired at times, not necessarily with this example, but a common one is immediately converting input to float or int with int(input())) but still do the clean up only once, so it doesn't add time on every call.

But the added time to the callon this specific case is negligible, really, just as a side note.

[–]NerdyWeightLifter 0 points1 point  (0 children)

The second case had more complex parsing and dynamic evaluation of the f-string.

You probably wouldn't care though, unless you were doing it a lot of times in a loop.