我需要编写一个python函数,它将字符串句子中的每个偶数单词大写,并且还反转该字符串中的每个奇数单词。 例如:
aString =" Michelle ma belle这些词汇很好地结合在一起#34;
bString =" MICHELLE是BELLE eseht是和我们一起蠢蠢欲动的"
我对如何做到非常基本的了解,但并非如此。
这是我到目前为止所拥有的......
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重新编译成新的字符串。这甚至可能吗?
答案 0 :(得分:1)
在你的代码中,你看的是单个字符,而不是单词。 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
将为每次迭代返回(index, value)
元组。
答案 1 :(得分:0)
计算机科学的一项基本规则是将问题分解为子问题。在您的情况下,我建议您首先将问题的解决方案分解为几个函数:
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