I am almost done with my code but I can't figure out two things.
First, I want to be able to say "You did not enter anything!" and end the program if a person enters zero characters in the string input at the beginning of the program.
Also, in the middle I have trouble figuring out how to use isalpha()
and isstring()
together. For example, if the string says, "dogs and cats" the program should output "Only alphabetic letters and spaces: yes."
However, if the string only has spaces or only has alphabetic letters then it should say, "Only alphabetic letters and spaces: no."
string = input('Enter a string: ')
length = len(string)
first_character = string[:1]
last_character = string[-1:]
print ('Length: ', length)
print ('First character: ', first_character)
print ('Last character: ', last_character)
if all(c.isalpha() or c.isspace() for c in string):
print('Only alphabetic letters and spaces: yes')
else:
print('Only alphabetic letters and spaces: no')
if string.isdigit():
print('Only numeric digits: yes')
else:
print('Only numeric digits: no')
if string.islower():
print('All lower case: yes')
else:
print('All lower case: no')
if string.isupper():
print('All upper case: yes')
else:
print('All upper case: no')
Take advantage of the fact that empty strings evaluate to False
:
string = input('Enter a string: ')
if not string:
print("Nothing entered.")
exit()
Use the built-in function all
to help you with the next part:
if not string.isalpha() and not string.isspace() and all(i.isalpha() or i.isspace() for i in string):
print("Passed!")
Well, after you get the length of the entered string with length = len(string)
, immediately perform your sanity check.
if length == 0:
# do something
You could check if a string is empty by using:
if (word1 == ''):
print('Empty')
Or if the string cointains whitespaces you could clear those out by using .strip()
word2 = ' '
word2a = word2.strip()
if (word2a == ''):
print('Empty2')
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.