0

Can anyone explain why its printing failed? word is a string but it keeps jumping to the else.

word = input("Enter a word.. ")
word_length = len(word)
first_letter = word[0]
last_letter = word[word_length-1]

if word == str:
    print(last_letter + word[1 : word_length-1] + first_letter)
else:
    print("failed")
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Lyres
  • 343
  • 4
  • 14
  • 1
    Did you try `print(word)` and `print(str)`? I think you'd be surprised at the results. – TigerhawkT3 Dec 10 '15 at 06:51
  • @thefourtheye: As [PEP 8](https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements), `word[word_length-1]` is recommended. – Remi Guan Dec 10 '15 at 06:53
  • By the way a simpler way to get the right-most letter in a string is to index from the right using a negative offset, for example `last_letter = word[-1]`. Negative offsets work with all Python sequences, which include string, lists, and tuples. – cdarke Dec 10 '15 at 07:23

1 Answers1

4

When you say

if word == str:

you are checking if the word is the same as the str() function.


If you want to check if the input is a string, then you can use the isinstance() function, like this

if isinstance(word, str):

But input() function, in Python 3.x, always returns a string only. So, you don't have to check if the input is a string or not.


Note: In case, you are using Python 2.x, print is actually a statement, not a function. You can read more about that in this question.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 1
    `if word == str:` checks against the string object. If he were using `if word == str():` then that's the same as checking if word is an empty string. As `str()` on it's own returns an empty string – Steven Summers Dec 10 '15 at 06:58