patternpythonMajor
Text message "reverser"
Viewed 0 times
messagetextreverser
Problem
I decided to step out of my comfort zone (Java) and try out Python. I wrote a very simple reverser.py and want it to be reviewed.
Examples in the terminal:
It would be great if I would be advised about:
"""
This python script basically takes a string and reverses it.
This python script can be used as a command line script as well as a separate
module.
"""
import sys
def reverse(message):
"""
This function takes a string and reverses it, so as to somewhat obfuscate
it.
:param message: The unencrypted text message to be reversed.
"""
text = ''
for character in message:
text = character + text
return text
if __name__ == '__main__':
numberOfArgs = len(sys.argv)
message = ''
if numberOfArgs == 1: # i.e. the program name only
message = input('Please enter the text to be encrypted : ')
elif numberOfArgs == 2:
message = sys.argv[1]
else:
print('Incorrect number of arguments : %d\n' % numberOfArgs)
print('Usage: python3 reverseCipher [unencrypted string]')
exit(2) # '2' stands for command-line syntax errors in unix
print(reverse(message))Examples in the terminal:
$ python3 reverser.py
Please enter the text to be encrypted : I understand that text manipulation in python is quite easy.
.ysae etiuq si nohtyp ni noitalupinam txet taht dnatsrednu I
$ python3 reverser.py "I am just starting out with python"
nohtyp htiw tuo gnitrats tsuj ma IIt would be great if I would be advised about:
- Code style and idioms
- The required mindset (for I have one for Java)
- Anything that can help me learn the language
Solution
This is going to be a short answer, but did you know Python has such a feature in-built?
Above would replace your
This is called extended slicing and has been added since Python 2.3. Slicing is a very easy to use method when handling array-like data.
The following illustrates how slicing and extended slicing can be used, executed in the interactive Python IDE:
As picture.
text = "I'm a stringy!"
print(text[::-1])Above would replace your
reverse method and is the most Pythonic way to solve this.This is called extended slicing and has been added since Python 2.3. Slicing is a very easy to use method when handling array-like data.
The following illustrates how slicing and extended slicing can be used, executed in the interactive Python IDE:
In [1]: text = "I'm a stringy!"
In [2]: print(text)
I'm a stringy!
In [3]: print(text[:-1])
I'm a stringy
In [4]: print(text[::-1])
!ygnirts a m'I
In [5]: print(text[:4:-1])
In [6]: print((text:4:-1] + text[:3:5])[::-1])
I stringy!
In [7]: print(text[::-1][::-1][::-1])
!ygnirts a m'I
As picture.
Code Snippets
text = "I'm a stringy!"
print(text[::-1])Context
StackExchange Code Review Q#111799, answer score: 20
Revisions (0)
No revisions yet.