r/ProgrammerHumor • • Nov 06 '20

Meme Totally agree

Post image
52.1k Upvotes

474 comments sorted by

View all comments

Show parent comments

113

u/Bainos Nov 07 '20

"Hello World!" - "World!" + "Bro!"

48

u/[deleted] Nov 07 '20

Wait does this actually work? I have been coding in python for years and I didn’t even know you could do this.

82

u/rogerrrr Nov 07 '20 edited Nov 07 '20

Unfortunately no, string subtraction is not supported.

However in Python 3.9 they added the string method .removesuffix, which serves a similar purpose.

So "Hello World".removesuffix("World") + "Bro" should get the job done.

71

u/itchy_bitchy_spider Nov 07 '20

Alternatively use replace... Support ed since forever I think lol

"Hello World".replace("World", "Bro")

8

u/[deleted] Nov 07 '20

Yeah I normally use this when I want to replace something in a string. Easy to read and short.

1

u/cheesits456 Nov 07 '20

Thats also valid JavaScript syntax! It only replaces the first instance of "World" though, if you have more than one, you'll need to use a regular expression, like "Hello World".replace(/World/g, "Bro") (idk if python is different in that regard)

Or, if that regular expression is too scary-looking, you could instead do "Hello World".split("World").join("Bro") 😎 /s

14

u/tailwarmer Nov 07 '20

String multiplication does, however, unfortunately work. Hello * 5 = HelloHelloHelloHelloHello

How do I know? A nasty production bug :(

4

u/_Dark____ Nov 13 '20

"haha string multiplication go b" + ("r"*69)

4

u/Chroneis Nov 07 '20

Yeah I wonder why it isn't... I guess it's too ambiguous?

0

u/[deleted] Nov 07 '20

[deleted]

2

u/Chroneis Nov 07 '20

Yeah, although I′m all for operator overloading when it makes sense (I really like how livescript handles a/b with a and b strings by making it do a.split(b), and a*b with a a list and b a string by making it do b.join(a)), it's quite difficult for substraction to be meaningful with a and b strings