Letter-based Strings not Recognized as Strings in Python Reversing

  • Thread starter WWGD
  • Start date
  • #1
WWGD
Science Advisor
Gold Member
5,631
5,063
Summary:
Algorithm correctly reverses numerical strings but does not recognize letter strings
Hi,
I have a simple Python algorithm in my Jupyter notebook , to reverse a string.
It works well on numerical strings, but when I try to reverse a letter string, I get an error message,
e.g., the string abc, I get the error message:
name 'abc' is not defined

This is my Python code

Python:
def reverse(x):
String=str(x)
if String[0]=='-':
return( '-' + str[:0:-1])
else:
return( str[::-1])
It works no problem with numerical input, e.g., if I enter:
reverse(-235), it returns -532

But if I try reverse(abc), I get the error message above:
"Name 'abc' not defined"

I have no idea what the issue could be. Any ideas?
 

Answers and Replies

  • #2
13,030
6,916
Look at your return statements I think you conflated the str() function with the variable String.

Personally I would use something more descriptive and less looking like a keyword ie I would use something like s instead of String.

Python:
s="hello"
s[::-1]
 
  • #3
WWGD
Science Advisor
Gold Member
5,631
5,063
Look at your return statements I think you conflated the str() function with the variable String.

Personally I would use something more descriptive and less looking like a keyword ie I would use something like s instead of String.

Python:
s="hello"
s[::-1]
Good point, but in my original code I did not make that mistake.
It was:
[code = python]
def reverse(x):
string=str(x)
if string[0]=='-':
return('-' + string[:0:-1])
else:
return(string[::-1])
[/code]
 
  • #4
13,030
6,916
okay your last return is missing a right paren at the end of the statement. Maybe that was the cause of your error message.
 
  • #5
WWGD
Science Advisor
Gold Member
5,631
5,063
Good point, but in my original code I did not make that mistake.
It was:
[code =python]
def reverse(x):
string=str(x)
if string[0]=='-':
return('-' + string[:0:-1])
else:
return(string[::-1]
[/code]
Summary:: Algorithm correctly reverses numerical strings but does not recognize letter strings

Hi,
I have a simple Python algorithm in my Jupyter notebook , to reverse a string.
It works well on numerical strings, but when I try to reverse a letter string, I get an error message,
e.g., the string abc, I get the error message:
name 'abc' is not defined

This is my Python code

Python:
def reverse(x):
String=str(x)
if String[0]=='-':
return( '-' + str[:0:-1])
else:
return( str[::-1])
It works no problem with numerical input, e.g., if I enter:
reverse(-235), it returns -532

But if I try reverse(abc), I get the error message above:
"Name 'abc' not defined"

I have no idea what the issue could be. Any ideas?

okay your last return is missing a right paren at the end of the statement. Maybe that was the cause of your error message.
Really sorry for my carelessness, Jedi, but I did not make that mistake in the original either. I will be extra careful to type in code correctly. The one you suggested does work without a problem.
 
  • #6
35,225
7,044
okay your last return is missing a right paren at the end of the statement. Maybe that was the cause of your error message.
Almost certainly that was the case.

This works:
Python:
def reverse(x):
    string=str(x)
    if string[0]=='-':
        return('-' + string[:0:-1])
    else:
        return(string[::-1])

str1 = 'abc'
str2 = reverse(str1)
print(str2)
 
  • #7
WWGD
Science Advisor
Gold Member
5,631
5,063
Ok, my problem was fixed just by using the original code but entering strings within double quotes, i.e.
reverse("stringname")
Go figure.
Edit: @Mark44 suggestion also worked out. Thank you both.
 
  • #8
Ibix
Science Advisor
Insights Author
2020 Award
8,307
7,711
Ok, my problem was fixed just by using the original code but entering strings within double quotes, i.e.
reverse("stringname")
Yes. The error is python telling you that it's never heard if a variable called abc. Adding quotes turns the input into the literal string you wanted. The program works with numeric input because numbers aren't legal variable names, so are always interpreted as literally what you typed. Your str(x) line turns it into the character string "532", which is then reversed.
 
  • #9
PeterDonis
Mentor
Insights Author
2020 Award
35,266
13,460
I have a simple Python algorithm in my Jupyter notebook , to reverse a string.
Why would you want to keep a "-" at the beginning for a string that doesn't contain all numeric characters?
 
  • #10
WWGD
Science Advisor
Gold Member
5,631
5,063
Why would you want to keep a "-" at the beginning for a string that doesn't contain all numeric characters?
True, but it seems it is used just in case it is numeric and ignored if it is not.
 
  • #11
PeterDonis
Mentor
Insights Author
2020 Award
35,266
13,460
True, but it seems it is used just in case it is numeric and ignored if it is not.
No, it isn't. There is no test anywhere in the code for an all-numeric string. It just tests for the first character being "-". So we would get, for example, reverse("-xyz") == "-zyx".
 
  • #12
PeterDonis
Mentor
Insights Author
2020 Award
35,266
13,460
This works
One note: there is no need for parentheses in the return statements. They work (since putting parentheses around any Python expression gives a valid Python expression), but they're not necessary.
 
  • #13
WWGD
Science Advisor
Gold Member
5,631
5,063
No, it isn't. There is no test anywhere in the code for an all-numeric string. It just tests for the first character being "-". So we would get, for example, reverse("-abc") == "-cba".
To address the example you brought up; that of -abc, -3ab, etc. , which may or may not be numeric.
 
  • #14
pbuk
Science Advisor
Gold Member
2,446
1,186
Are you using a, b, c... as hexadecimal digits? If so:
  • This is not the way to do it, you want -0x3ab
  • Reversing digits of a decimal number and a hexadecimal number are different operations so mixing them in the same program is undesirable
What are you actually trying to do?
 
  • #15
WWGD
Science Advisor
Gold Member
5,631
5,063
Are you using a, b, c... as hexadecimal digits? If so:
  • This is not the way to do it, you want -0x3ab
  • Reversing digits of a decimal number and a hexadecimal number are different operations so mixing them in the same program is undesirable
What are you actually trying to do?
These are interview questions. This question was about an algorithm to reverse strings; no more context was given.
 
  • #16
PeterDonis
Mentor
Insights Author
2020 Award
35,266
13,460
To address the example you brought up; that of -abc, -3ab, etc. , which may or may not be numeric.
Yes, but "-xyz" is clearly not, yet it behaves the same way; see post #11.
 
  • #17
Ibix
Science Advisor
Insights Author
2020 Award
8,307
7,711
If it's an interview question presumably you are expected to both diagnose the immediate error (abc is interpreted as a variable which is undefined) and point out that the function behaviour is peculiar if you are not feeding it a number, perhaps leading into a discussion on validating your inputs. So Peter gets thr job...
 
  • #18
Nugatory
Mentor
13,498
6,605
One note: there is no need for parentheses in the return statements. They work (since putting parentheses around any Python expression gives a valid Python expression), but they're not necessary.
And this note is not just a quibble. The parentheses make the statement syntactically indistinguishable from a function invocation. This matters if we just happen to fat-finger the spelling of “return” in an infrequent code path that isn’t executed by our test suite - the parentheses have turned a compile-time syntax error during development into a run-time crash of a production system.
 

Related Threads on Letter-based Strings not Recognized as Strings in Python Reversing

  • Last Post
Replies
15
Views
2K
  • Last Post
Replies
1
Views
1K
Replies
9
Views
881
  • Last Post
Replies
3
Views
1K
Replies
5
Views
22K
Replies
3
Views
718
  • Last Post
Replies
5
Views
6K
  • Last Post
Replies
19
Views
3K
  • Last Post
Replies
7
Views
5K
Replies
5
Views
1K
Top