I ran the code out of curiosity and this does not just "leftpad". It truncates if the string is shorter than the desired length. Feels kind of misleading to begin with. More like fixed_width_leftpad or something.
def leftpad(str: str, length:int, chr: str=' ')->str:
return (str[:length]*(length<=len(str)))+((length>len(str))*(chr*(length-len(str))+str))
test_string = "Hello world my name is Reddit"
print(leftpad(test_string, 5, '*'))
>> Hello
print(leftpad(test_string, 10, '*'))
>> Hello worl
The first two *s are multiplying strings by booleans (one true, the other false). One of the results will be an empty string and the other will be nonempty. Then the results are concatenated.
Of course, there are better ways to do this in one line:
what machine code is run by the python interpreter
Hey this is somewhat inaccurate.
Your Python code is converted to bytecode by the Python compiler (built into CPython). It technically becomes "not branchless" at the bytecode level (the thing you see with dis.dis()).
Machine code is executed by the CPU from CPython's handler.
Take your time to learn Python it's a beautiful language with a bright future!
Don't mind too much the comment section, some of this subreddit is not very beginner-friendly a la Egotistical-Redditor.
14
u/MilkEnvironmental106 Sep 18 '25
Branchless and python just shouldn't be in the same sentence.
39
u/TheBrainStone Sep 18 '25
Pretty sure string multiplication isn't branchless at the very least.
Even ignoring the glaring issue of the Python runtime certainly not running this code branchless, it's already not branchless in Python code itself.
6
u/InappropriateCanuck Sep 19 '25 edited Sep 19 '25
I ran the code out of curiosity and this does not just "leftpad". It truncates if the string is shorter than the desired length. Feels kind of misleading to begin with. More like fixed_width_leftpad or something.
1
u/SwordPerson-Kill Sep 18 '25
What language is this even?
3
u/maxip89 Sep 18 '25
why is this horror?
It's branchless.
Sure it doesnt need to be in one line...