-1
\$\begingroup\$

I'm learning how to reverse list and strings. Is there another way of reversing a string other than using [::-1] method? even if the other method is the long route i would much appreciate it

txt = ["Hello World"] st ="".join(txt) print(st[::-1]) 
\$\endgroup\$
4
  • 3
    \$\begingroup\$There's really not much code here to review. "Missing Review Context: Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." This seems generic/stub, not a complete application.\$\endgroup\$
    – ggorlen
    CommentedSep 21, 2022 at 13:35
  • \$\begingroup\$(print("".join(reversed(txt)))?)\$\endgroup\$
    – greybeard
    CommentedSep 25, 2022 at 12:25
  • \$\begingroup\$I’m voting to close this question because there is no code to review: The question is squarely off-topic at CR.\$\endgroup\$
    – greybeard
    CommentedSep 25, 2022 at 12:30
  • \$\begingroup\$(Putting a string literal in a list to go on and ''.join() it is pointless: print("Hello World"[::-1]).)\$\endgroup\$
    – greybeard
    CommentedSep 25, 2022 at 12:36

2 Answers 2

5
\$\begingroup\$

Using string slicing as you have done is pretty much the best way, as discussed in this answer.

You should consistently put a space before and after the = assignment operator, as recommended by PEP 8, the official Python style guide:

  • Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).
\$\endgroup\$
0
    2
    \$\begingroup\$

    Is there another way of reversing a string other than using [::-1] method?

    Yes there is. There are plenty of tutorials on the Internet, consider this one for example: Python Reverse String - 5 Ways and the Best One. What's interesting is the performance comparison between the different options. Achieving best performance will usually be your goal, unless that makes the code too obscure or inflexible.

    The [::-1] is recommended because it is fast, short and to the point (and Pythonic). I don't have a better suggestion for you.

    But to address your code specifically, it can be simplified since Python strings, like lists or tuples, are sequences. So for your purpose the string can be handled like a list:

    txt = "Hello World" print(txt[::-1]) 

    If you don't like the notation because you find it unusual, just write a function.

    \$\endgroup\$
    1
    • \$\begingroup\$aahh that's interesting\$\endgroup\$CommentedSep 21, 2022 at 21:04

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.