簡體   English   中英

如果句子中的所有單詞都是小寫,我如何返回“是”?

[英]How do I return "Yes" if all words in the sentence are lowercase?

我目前可以讓我的代碼為每個字符返回“是”,但是如果句子中的每個單詞都是小寫,我不確定如何讓代碼在代碼末尾只返回一個 Yes 這是我所擁有的

sentence = "hello thEre is this aLL lowercase"
sent = sentence.split(" ")
lower = False
for wd in sent:
    for ch in wd:
        if ch.islower():
            print("Yes")
            lower = True
        if not ch.islower():
            print("No")
            lower = False

我知道我不能在循環中使用 print("Yes") 因為它每次都會打印,但我不知道如何以其他方式進行。 謝謝你的幫助。

這是接近解決方案的一種方法。

我故意不提供任何解釋,因為這將有助於您學習自己研究這些概念。 調查:

  • 列表理解
  • all()函數
  • 布爾測試

示例代碼:

s = ‘lower case statement’

result = all([i.islower() for i in s.split()])

print('Yes' if result else 'No')
>>> ‘Yes’

我建議將短代碼的每一部分分開,以了解它是如何工作的。

簡化:

就個人而言,我不介意在教育環境中分享這一點,因為學習編寫 Python(以及一般代碼)的一部分就是學習高效地編寫它。 也就是說,這是一個簡化的解決方案:

print('Yes' if s.islower() else 'No')
>>> ‘Yes’

我假設這是一個練習,所以我不會給出任何代碼。

您需要有一個變量“找到的任何非小寫單詞”,該變量在循環之前設置為 false,如果找到不是小寫的單詞,則設置為 true。 如果循環后變量仍然為假,您可以打印“是”,否則不會。

也許如果您編寫了實現此功能的代碼,您會發現它是可以優化的。

您可以使用isLower() ,只需記住刪除空格

def checkLower(string):
    string = string.replace(" ","")
    print(string)
    for i in string:
        if i.islower() == False:
            return "no"
    return "yes"

如果您只關心它是否全部小寫,那么當您第一次找到大寫字母時,您應該跳出循環。 如果在循環外為 true,則僅打印 yes。

您可以使用.islower()簡單地這樣做,因為如果字符串中的所有字符都是小寫,則islower()方法返回True ,否則返回False

sentence = "hello thEre is this aLL lowercase"
if(sentence.isLower()):
    print('Yes')
else:
    print('No')
sentence = "hello there this is all lowercase"
sent = sentence.split(" ")
lower = True
for wd in sent:
    for ch in wd:
        if not ch.islower():
            lower = False
if lower:
   print("Yes")
if not lower:
   print("No")

我對 python 及其工作原理不太了解,但這是我添加到提供的代碼中的邏輯。

現在,每次找到小寫單詞時,您都在打印“是”。

def isAllLower(sentence):
    sent = sentence.split(" ")
    lower = False
    for wd in sent:
        for ch in wd:
            if ch.islower():
                lower = True
            if not ch.islower():
                lower = False
    if lower == True:
        print("Yes")
    elif lower == False:
        print("No")

isAllLower("hello thEre is this aLL lowercase")

迄今為止最簡單的方法是使用lower()函數將默認降低的句子與初始函數進行比較!

def SentenceisLower(sentence):
    sentencelower = sentence.lower()
    if (sentence == sentencelower):
        print("Yes!")

哪里有其他結果沒有回復!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM