You can use the str.startswith() method to test if a string starts with a specific character; the method takes either a single string, or a tuple of strings:
if s.lower().startswith(tuple('aeiou')):
The str.startswith() method doesn't care if s is empty:
>>> s = ''
>>> s.startswith('a')
False
By using str.lower() you can save yourself from having to type out all vowels in both lower and upper case; you can just store vowels into a separate variable to reuse the same tuple everywhere you need it:
vowels = tuple('aeiou')
if s.lower().startswith(vowels):
In that case I'd just include the uppercase characters; you only need to type it out once, after all:
vowels = tuple('aeiouAEIOU')
if s.startswith(vowels):
Answer from Martijn Pieters on Stack OverflowYou can use the str.startswith() method to test if a string starts with a specific character; the method takes either a single string, or a tuple of strings:
if s.lower().startswith(tuple('aeiou')):
The str.startswith() method doesn't care if s is empty:
>>> s = ''
>>> s.startswith('a')
False
By using str.lower() you can save yourself from having to type out all vowels in both lower and upper case; you can just store vowels into a separate variable to reuse the same tuple everywhere you need it:
vowels = tuple('aeiou')
if s.lower().startswith(vowels):
In that case I'd just include the uppercase characters; you only need to type it out once, after all:
vowels = tuple('aeiouAEIOU')
if s.startswith(vowels):
This will check the boolean value of s first, and only if it's True it will try to get the first character. Since a empty string is boolean False it will never go there unless you have at least a one-character string.
if s and s[0] in ["a","e","i","o","u","A","E","I","O","U"]:
print("an", s)
Just move your logic inside the first if check
word = raw_input("type a word, any word")
if word.isalpha() and len(word) > 0:
first = word[0]
rest = word[1:len(word)]
ay = "ay"
print (rest + first + ay)
elif len(word) == 0:
print "invalid entry"
else:
print "invalid entry"
You only need to check if word as empty strings evaluate to False and use a single else statement, your second elif is unnecessary as the word will either have a least one char and be alpha or not:
word = raw_input("type a word, any word")
if word.isalpha() and word:
first = word[0] # will only try to index if word is not an empty string or not alpha
rest = word[1:len(word)]
ay = "ay"
print (rest + first + ay)
else:
print "invalid entry"
In [11]: bool("")
Out[11]: False
In [12]: bool("foo")
Out[12]: True
You can also use ternary conditional operator
word = raw_input("type a word, any word")
print word[1:] + word[0] + "ay" if word.isalpha() and word else "invalid entry"
Hey guys I am trying to create a contact book in python and need help with something. Basically when you want to create a contact I want the program to check each of the values in the list of contact names and when it finds the first empty value that is the one that will be overwritten. If there were no empty values I would ask the user which one they overwrite. So how do I do this? I have looked online and they all talk about finding non-empty string but none are about selecting the first empty string. I would prefer if I don't have to resort to a giant stack of if statements to get this done. here is my code so far if it helps:
contact_names = ["","","","","","","","","","","","","","","","","","","","a"]
contact_numbers = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
contact_email = ["","","","","","","","","","","","","","","","","","","",""]
selection = 0
# This is a contact book to save contacts
print ("Contact book")
print ("By MarketingZestyclose7")
input('Press ENTER to continue')
print ("Would you like to (V)iew contacts or (C)reate contacts?")
#This is a while loop that 'traps' the user until they make a valid selection (V or C)
while (selection != "V") and (selection != "C"):
selection = input()
if (selection != "V") and (selection != "C"):
print ("Incorrect Entry! Retry")
if selection == "C":
if contact_names[19] == "":
print ("test")The index method gives you the first index where the space appears in the list. This isn't limited to just empty strings, but any character/string that appears twice in the list. Use enumerate to have a counting variable instead.
def number(lines):
return ['{0}: {1}'.format(i+1, j) for i, j in enumerate(lines)]
if you dont want blank string then try
return ['{0}: '.format(lines.index(i) +1) + i for i in lines if i!='']
Try:
if l[i]:
print 'Found element!'
else:
print 'Empty element.'
Just check if that element is equal to None type or make use of NOT operator ,which is equivalent to the NULL type you observe in other languages.
if not A[i]:
## do whatever
Anyway if you know the size of your list then you don't need to do all this.
I've been trying to run my script using
python run.py test modules
Argument 0: run.py
Argument 1: test
Argument 2: modules
I've been getting this error then:
Traceback (most recent call last):
File "run.py", line 57, in <module>
if str(sys.argv[2]) == str() or str(sys.argv[2]) == "coverage" or str(sys.argv[3]) == "coverage":
IndexError: list index out of rangeWhy is the list index out of range? I've already given that if str(sys.argv[3]) == str(), where str() denotes empty string, then the condition should hold true.Where am I going wrong?
When slicing a string in Python, the string[100:105], the operation was designed specifically to fail gracefully. The result of an out of range slice is to return the empty string ''. See the Informal Introduction for more information.
Accessing a specific index of a string, the string[100] was not designed to fail gracefully, so it raise an exception.
String slicing in python will not raise errors, they will just return the string that you were looking for (in this case, it's indeed a empty string because there's nothing there).
Slicing returnes a subsequence of items, and it doesn't do any bound checking. If the wanted data (memory) is empty, it will send back an empty string as you got.