Using endswith in python

Realtime20
Realtime20 used Ask the Experts™
on
Hello,

I am learnging python and need a little help. I am trying to use "str.endswith()" but having a hard time for some odd reason.

I am trying to figure out if a sentence ends with a "." but have been unable to do so....

Thanks in advance.
#!/usr/bin/env python

text = input("Add sentence here: ")

if text.endswith('.'):
   print("sentence closed correctly")
else:
   print("please end the sentence with . ")

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
The code you give works as it should in Python 3.1 but not in Python 2.7

To work in python 2.7 you have to replace input with raw_input so it should become:

text = raw_input("Add sentence here: ")

if text.endswith('.'):
   print("sentence closed correctly")
else:
   print("please end the sentence with . ")

That is because in Python 2.7 input is equivalent to eval(raw_input(prompt)) and in python 3.x raw_input is equivalent to input.

Author

Commented:
Thanks for the quick reply.

I am using python 3.0.

I still tried "raw_input" for giggles and it did not work. I haven't been able to figure this out...

Author

Commented:
You are correct though as i have version 3.1 installed and it works correctly.
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

Can you clarify what you mean by doesn't work? If you copy/paste your code in python 3.x or the code I gave you in Python 2.7 it works as expected i.e.: (output):

>>> ================================ RESTART ================================
>>> 
Add sentence here: hello
please end the sentence with .
>>> ================================ RESTART ================================
>>> 
Add sentence here: hello.
sentence closed correctly
>>> 

waiting for your feedback

Author

Commented:
if i copy and paste my code from 3.0 to 3.1 it works. It is not working in python 3.0.  

The whole issue was with versions. I should have just checked my Linux workstation instead of using windows :(

Thanks again though.
To set the record straight it definitely works also with python 3.0.1 (I checked it before my previous comment) that's why I wrote python 3.x.

You are welcome,

John.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial