0

I am trying to check the input to see if it has any extension here is the code I used:

filename=input()
if "." in filename:
    print ("There is")

However this will return "there is" even if the input is ends with just a full stop.
Is there any way to check if the input has any letters after the "."? I can't specify what the extension should be (as it is up to the user), just that there should be an extension.

J.Doe
  • 1
  • 2
  • Possible duplicate of [Extracting extension from filename in Python](http://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python) – rfkortekaas Sep 04 '16 at 17:56

3 Answers3

2

An easy option would be to check for "." in filename with the last character removed:

if len(filename)>1 and "." in filename[:-1]:
    print("there is")

This would allow "file..", which may or may not be what you want. Another idea would be, to split filename at every "." and check that you get at least two parts, the last of which is non-empty:

parts = filename.split(".")
if len(parts) > 1 and parts[-1]:
    print("there is")

This will not allow "file..", but will allow "file.,". If you want to only allow extensions which consist of letters, you should probably use regular expressions. For example, you could try the following:

import re
m = re.match('[a-z]*\.[a-z]+', filename)
if m:
    print("there is")

This will allow "file.txt", but not "a.b.c". Regular expressions are very flexible and this approach can be extended to check for quite specific name formats.

jochen
  • 3,728
  • 2
  • 39
  • 49
0

I used the find function to locate the character . in me. If the character doesn't exist in me, the function returns -1. Then, with the index of the . character, I see if there are any characters after that index with len(me[index + 1:]). If the len function returns a positive number, then you know there are characters after the . character.

me=input()
index = me.find(".")
if (index != -1 and len(me[index + 1:]) > 0):
    print ("There is")

It might not be the most elegant way to solve this with Python, but it covers the basics of your problem without getting too fancy.

Xetnus
  • 353
  • 2
  • 4
  • 13
0

Split the string on the dot and check to see if there was anything after it.

s = 'aaa.'
if s.strip().split('.')[-1]:
    print('extension')
else:
    print('no extension')
s = 'aaa.bbb'
if s.strip().split('.')[-1]:
    print('extension')
else:
    print('no extension')
wwii
  • 23,232
  • 7
  • 37
  • 77