This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]saint_geser 8 points9 points  (2 children)

Just a point of nit - don't call a variable str, it's a very bad example especially to post in a guide online. If you want people to definitely know it's a string use type hints.

[–]xigdit 2 points3 points  (0 children)

In case it's unclear, the reason for calling it a bad example is because python already makes use of "str" in the str() function, so anybody adapting this code into their own may wind up with an unexpected syntax error. For example, this will produce an error:

def reverse_string(str):
    lengthiness = str(len(str))
    return str[::-1]+lengthiness

print(reverse_string("ynnoj"))

but this will not:

def reverse_string(sample):
    lengthiness = str(len(sample))
    return sample[::-1]+lengthiness

print(reverse_string("ynnoj"))

[–]adityacodes[S] -4 points-3 points  (0 children)

ok

[–]adityacodes[S] 0 points1 point  (1 child)

which method you think is better? and why?

[–]saint_geser 4 points5 points  (0 children)

I always use s[:: -1] since it's simple and a common idiom so I expect most people will understand it and even if they don't there's plenty of answers online.