如何在字符串中反转/大写单词

3

我需要编写一个Python函数,将字符串中的每个偶数单词大写,并反转该字符串中的每个奇数单词。

例如:

aString = "Michelle ma belle these are words that go together well"

bString = "MICHELLE am BELLE eseht ARE sdrow THAT og TOGETHER llew "

我对如何实现有非常基础的理解,但不是很清楚。

这是我目前的进展...

def RewordProgram(a):
    L = input("enter a sentence, please")
    if L[0:][::2]:                  # for even words
        b = L.upper()
        return b  
    else if L[1:][::2]:              # for odd words
        c = L[::-1] 
        return c

请问有人能帮我理解我错在哪里吗?我的if else函数不能正常工作,而且我不知道如何将b和c重新编译成一个新的字符串。这是否可能呢?


我在你原始代码中添加了更多的注释。同时再次强调,“print”在这里是你的好朋友! - Grimmy
2个回答

2
在你的代码中,你正在查看单个字符而不是单词。L是一个字符串,所以你需要使用split()来获取单词。如果你是一个初学者,尽可能多地打印出来是个好主意。打印L[0:]和L[0:][::2]的值将非常有帮助,这样可以告诉你执行的路径。
实际上,L[0:][::2]只返回整个字符串的每第二个字符。L[0:]与L相同,因为它从索引0创建一个字符串到字符串的结尾...然后[::2]跳过每第二个字符。 print是你的朋友!...也许与调试器一起使用,但打印也可以完成任务。
你可以用生成器表达式解决这个问题:
text = "Michelle ma belle these are words that go together well"
r = ' '.join(w[::-1] if i % 2 else w.upper() for i, w in enumerate(text.split()))
print(r)

这段话的详细版本是(不那么吓人):
words = []
for i, w in enumerate(text.split()):
    # odd
    if i % 2:
        words.append(w[::-1])
    else:
        words.append(w.upper())
print(" ".join(words))

注意使用enumerate,它会为每个迭代返回一个(索引, 值)元组。


1
计算机科学中的一个基本规则是将问题分解为子问题。在您的情况下,我建议您从将解决方案分解为几个函数开始:
  • words 接受字符串作为参数并返回其中包含的单词列表。
  • upcase 返回大写字符串。
  • reverse 反转字符串。

一旦您编写了这些函数,您将需要其他函数来将它们组合在一起。您需要:

  • 一种方法为单词列表中的每个单词添加索引(提示:enumerate)。
  • 一种方法将过程应用于具有索引的单词列表中的每个项(提示:map)。

完整的代码如下。我建议您不要立即阅读它,而是在遇到上述步骤中的任何一步时使用它作为帮助。

剧透警告:以下为解决方案

# This function reverses the word. It's a bit tricky: reversed returns an    
# enumerator representing a sequence of individual characters. It must be    
# converted into a string by joining these characters using an empty string. 
def reverse(string):                                                         
    '''Reverse a string.'''                                                  
    return ''.join(reversed(string))                                         

# Upcasing is simpler. Normally, I would've inlined this method but I'm leaving
# it here just to make it easier for you to see where upcasing is defined.   
def upcase(string):                                                          
    '''Convert the string to upcase.'''                                      
    return string.upper()                                                    

# Normally, I'd use the split function from the re module but to keep things 
# simple I called the split method on the string and told it to split the string
# at spaces.                                                                 
def words(string):                                                           
    '''Return a list of words in a string.'''                                
    return string.split(' ')                                                 

# This is your function. It works as follows:                                
#                                                                            
# 1. It defines an inner function _process_word that takes the index of the word
#    and the word itself as arguments. The function is responsible for       
#    transforming a single word.                                             
# 2. It splits the string into words by calling words(string).               
# 3. It adds a zero-based index to each of the words with enumerate.         
# 4. It applies _process_word to each and every item of the sequence in 3.   
# 5. It joins the resulting words with spaces.                               
def capitalize_and_reverse(string):                                          
    def _process_word((index, word)):                                        
        if index % 2 == 0:                                                   
            return upcase(word)                                              
        else:                                                                
            return reverse(word)                                             

    return ' '.join(map(_process_word, enumerate(words(string))))            


string = "Michelle ma belle these are words that go together well"           
print capitalize_and_reverse(string)                                         
# MICHELLE am BELLE eseht ARE sdrow THAT og TOGETHER llew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接