Letter-based Strings not Recognized as Strings in Python Reversing

  • Thread starter WWGD
  • Start date
  • #1
WWGD
Science Advisor
Gold Member
6,326
8,380
TL;DR 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
14,284
8,310
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
6,326
8,380
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
14,284
8,310
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
6,326
8,380
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
36,858
8,903
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
6,326
8,380
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
2022 Award
10,339
11,100
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
41,291
18,919
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
6,326
8,380
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
41,291
18,919
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
41,291
18,919
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
6,326
8,380
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
Homework Helper
Gold Member
4,084
2,411
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
6,326
8,380
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
41,291
18,919
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
2022 Award
10,339
11,100
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
14,210
8,097
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.
 

Suggested for: Letter-based Strings not Recognized as Strings in Python Reversing

  • Last Post
Replies
10
Views
1K
Replies
17
Views
543
Replies
2
Views
441
Replies
4
Views
106
  • Last Post
Replies
4
Views
907
Replies
5
Views
461
Replies
10
Views
454
Replies
13
Views
1K
  • Last Post
4
Replies
118
Views
5K
  • Last Post
Replies
1
Views
114
Top