简体   繁体   中英

How to check for certain characters at the end of a user input? Python

My program asks the user to enter the name of a file that they want opened.

If they put .txt at the end, the file will be opened.

How can I make my program prevent non- .txt extensions, so that my program will add it on anyway so that the correct program gets entered.

There is already the string method .endswith

>>> 'test.txt'.endswith('.txt')
True
>>> 'test.png'.endswith('.txt')
False

If it does not already end with the correct extension, you'll have to think of what inputs you could possible get and add it for them. This could be either the wrong kind of extension or no extension. This could get tricky to catch all the edge cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM