r/badcode • • Jan 30 '21

python Why use strip, when this does the trick?

Post image
998 Upvotes

49 comments sorted by

72

u/DripDropFaucet Jan 30 '21

This ones kind of wholesome, would this ever iterate more than once?

63

u/QuidoPepek Jan 30 '21

Well this was code written for a discord bot to parse a message, so if someone wrote something with many spaces in the beginning, it would.

4

u/TimGreller Jan 30 '21

Doesn't Discord strip leading and trailing spaces (and linebreaks) automatically?

12

u/LeeHide Jan 30 '21

yes but with a bot you can have things like

!mybot      do_thing

and those spaces will remain, and are at the beginning of the command if split by first space after !mybot

4

u/[deleted] Jan 30 '21

Shlex.split is your friend. Strips those white spaces for you, and groups things in quotes by default.

1

u/QuidoPepek Jan 30 '21

I don't know, but this wasn't for the entire message, but for a section of it

Edit: like u/LeeHide has said

1

u/TimGreller Jan 30 '21

yes, that makes sense :)

24

u/glasshalf3mpty Jan 30 '21

If it had more than one space at the start, wouldn't it return an empty string?

Edit: I just looked up what the second argument of split means, don't mind me.

16

u/DragonNinja386 Jan 30 '21

I don't think so. It looks like the code only splits off the front most space each time, leaving any additional spaces connected to the string.

1

u/ign1fy Jan 31 '21

...and it would probably malloc() on every iteration. Painfully slow.

147

u/Dctcheng Jan 30 '21

I don't want Nick stripping

53

u/005eelmarag Jan 30 '21

I do

30

u/pantlesspatrick Jan 31 '21

Did you know that Cardi B has a sister who is really into fitness? Her name's Cardi O

1

u/TheAnxiousDeveloper Jan 31 '21

Only if he's Nick Scratch from Sabrina.

1

u/dabombnl Jan 31 '21

But I'm already naked.

32

u/MADH95 Jan 30 '21

I love this sub because it teaches me what not to do lmao

20

u/alfiestoppani Jan 30 '21

I’ve been coding as a hobby for about 3 years and I only learned about strip this week! It’s been a good week. 🦄

9

u/BlueMarble007 Jan 30 '21

Good on you dude! If you want to learn some more things to avoid, look up the SonarSource rules

6

u/alfiestoppani Jan 30 '21

Thanks for the tip. Very useful indeed. 🦄

14

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 30 '21

Image Transcription: Code


while nick.startswith(" "):
    temp = nick.split(" ", 1)
    nick = temp[1]

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

9

u/veryusedrname Jan 30 '21

<irony> Well, do you know the bigO for strip from the top of your head? No? This is O(n) for worst! </irony>

1

u/MysticTheMeeM Jan 31 '21

O(n) and a bunch of copies, where you could reasonably have only one.

3

u/Atsch Jan 31 '21

Python .strip is cursed though, so this is understandable

1

u/RFC793 Jan 31 '21

How is it cursed? Only thing I can think of is that it considers all white space chars. lstrip(' ') should be functionally equivalent to OP’s code.

1

u/Atsch Jan 31 '21

.strip does not consider the string to be a sequence of characters to remove, but a set of them. so "aabbccbcbcbcbcbdef".strip("abc") == "def"

1

u/RFC793 Jan 31 '21 edited Jan 31 '21

Of course, but he is just removing whitespace. It isn’t cursed it does exactly what it says it does; it strips all leading and/or trailing instances of the specified characters. Assuming you want to remove all instances of a substring then you want something entirely different:

"aabbccbcbcbcbcbdef".replace("abc", "") == 'aabbccbcbcbcbcbdef'

1

u/Atsch Jan 31 '21

You say "of course", but misunderstanding what .strip does is such a common issue that PEP was written to add .removeprefix/suffix functions to try to stop it from happening: https://www.python.org/dev/peps/pep-0616/

1

u/RFC793 Feb 01 '21

Funny. I was going to mention those functions from 3.9 to provide an alternative for what you may have meant.

Maybe “trim” is a better term than “strip”, but it makes perfect sense. It is for the common case of removing trailing and leading whitespace. I don’t understand what is “problematic” about that. Indeed reviewing PEP616 rational show that some people misuse the function. But, if you don’t read the docs then you are a bad programmer, and will ultimately write bad code.

The docs state, on the first page: “String specifying the set of characters to be removed.”. SET. It says SET. There is nothing problematic about this function other than fools who want to use tools without RTFM. And if you didn’t catch this during testing, then you are even worse.

4

u/jarfil Jan 31 '21 edited Dec 02 '23

CENSORED

11

u/FloweyTheFlower420 sadistic Jan 31 '21

sike, python doesnt have a compiler

1

u/RFC793 Jan 31 '21 edited Jan 31 '21

It kind of does. Python code is compiled to python bytecode prior to execution. However, it isn't able to perform any real optimizations.

>>> import dis
>>> def g():
...     r = 0
...
>>> dis.dis(g)
  2           0 LOAD_CONST               1 (0)
              2 STORE_FAST               0 (r)
              4 LOAD_CONST               0 (None)
              6 RETURN_VALUE

python has an optimization flag (-O), but I'm not sure what it does. When running this test case above from a script file as python -O test.py, the same bytecode is displayed.

3

u/SpaceNinjaDino Jan 31 '21

Not possible. The intention vs code here is beyond what a compiler would apprehend.

2

u/TheSunSide Jan 31 '21

For anyone wondering .Split of python should remove all associated chars from the string and this should return a list without any spaces whatsoever unless I’m mixing it up

3

u/cheerycheshire Jan 31 '21

Second argument shows how many splits it does. So this would split only one, thus returning a two-element list: an empty string (because there's nothing before first space...), and the rest of the string (which it used).

That's why I said in another comment that nick = nick[1:] would be slightly better (we know the first char is not needed, we don't need to split and throw out an empty string)...

1

u/JakeN9 Jan 31 '21

what he wants is .trim()

1

u/RFC793 Jan 31 '21 edited Jan 31 '21

wtf is .trim()? He wants .lstrip().

But chances are, there is another similar loop after this to remove trailing space. In which case .strip() will handle it all.

1

u/JakeN9 Feb 01 '21

Try .trim() in your javascript console

1

u/RFC793 Feb 01 '21

Yeah, but that doesn’t help this Python code.

1

u/cheerycheshire Jan 31 '21

It would be slightly better to just do

nick = nick[1:]

1

u/[deleted] Jan 31 '21

I don't know about Python's tools, but would something along the lines of replaceFirst(/ */, "") work?

I mean, there's probably a library that does include it anyways.

1

u/bnhalder Aug 11 '22

Strip removes extra unnecessary characters from the beginning and end of a string. You can pass the characters to remove as an argument. If you don't pass anything, it'll remove spaces. You can check out this 2 min YouTube video which demonstrates how to do this code - https://youtu.be/SMDKfIWiLDM

-8

u/kadenjtaylor Jan 30 '21

Can we please stop using this subreddit to penalize people for not knowing stuff?

Or, failing that, can we at least have some special designation for a probably novice programmer who just didn't know a particular function existed already?

15

u/QuidoPepek Jan 30 '21

I'm not mocking the person who wrote this, I'm mocking the code itself.

Besides, isn't most bad code written because of people not knowing stuff?

2

u/speedingpeanut Jan 31 '21

Yeah it's a bit of a catch 22, but I've certainly seen people go against the grain and write bad code purely for job security

2

u/RFC793 Jan 31 '21

Indeed. Sure, a coder might not know about strip, but the continuous construction of strings is what makes it bad to me. Something like this isn't great, but not "bad":

start = 0
while nick[start] == ' ':
    start += 1
nick = nick[start:]

13

u/mrbutthead86 Jan 30 '21

Then what is this subreddit for? Everybody writes bad code due lack of knowledge. I am a developer for more than 10 years now. Still there are code snippets of me from recent years and months I can laugh about. Self reflection is the keyword.

1

u/[deleted] Feb 14 '21

[removed] — view removed comment

1

u/AutoModerator Feb 14 '21

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/itsm1kan, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.