[英]Having trouble with figuring out how to loop and use isalpha() and isspace() together in a String Report
我的代碼幾乎完成了,但是我無法弄清楚兩件事。
首先,我希望能夠說“您沒有輸入任何內容!” 如果有人在程序開頭輸入的字符串中輸入零字符,則結束程序。
另外,在中間,我很難弄清楚如何一起使用isalpha()
和isstring()
。 例如,如果字符串說“狗和貓”,則程序應輸出“僅字母和空格:是”。
但是,如果字符串僅包含空格或僅包含字母,則應顯示“僅字母和空格:否”。
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')
利用空字符串評估為False
的事實:
string = input('Enter a string: ')
if not string:
print("Nothing entered.")
exit()
使用內置函數all
可以幫助您進行下一部分:
if not string.isalpha() and not string.isspace() and all(i.isalpha() or i.isspace() for i in string):
print("Passed!")
好了,獲得長度為length = len(string)
的輸入字符串的length = len(string)
,請立即執行健全性檢查。
if length == 0:
# do something
您可以使用以下命令檢查字符串是否為空:
if (word1 == ''):
print('Empty')
或者如果字符串包含空格,則可以使用.strip()清除空格
word2 = ' '
word2a = word2.strip()
if (word2a == ''):
print('Empty2')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.