string = "Here is my dog"
def alternateUppercase(s):
i = 0
a = s.split(' ')
l = []
for w in a:
if i:
l.append(w.upper())
else:
l.append(w)
i = int(not i)
return " ".join(l)
print alternateUppercase(string)
import re
text = """The 1862 Derby was memorable due to the large field (34 horses),
the winner being ridden by a 16-year-old stable boy and Caractacus'
near disqualification for an underweight jockey and a false start."""
def selective_uppercase(word, index):
if index%2:
return str.upper(word)
else:
return word
words, non_words = re.split("\W+", text), re.split("\w+", text)
print "".join(selective_uppercase(words[i],i) + non_words[i+1] \
for i in xrange(len(words)-1) )
输出量:
The 1862 Derby WAS memorable DUE to THE large FIELD (34 HORSES),
the WINNER being RIDDEN by A 16-YEAR-old STABLE boy AND Caractacus'
NEAR disqualification FOR an UNDERWEIGHT jockey AND a FALSE start.
user_word_2 = "I am passionate to code"
#block code to split the sentence
user_word_split_2 = user_word_2.split()
#Empty list to store a to be split list of words,
words_sep =""
#block code to make every alternate word
for i in range(0, len(user_word_split_2)): #loop to make every second letter upper
if i % 2 == 0:
words_sep = words_sep + " "+ user_word_split_2[i].lower()
else:
words_sep = words_sep +" " + user_word_split_2[i].upper()
#Block code to join the individual characters
final_string_2 = "".join(words_sep)
#Block code to product the final results
print(final_string_2)
6条答案
按热度按时间bgtovc5b1#
nfg76nw02#
我认为您要寻找的方法是
upper()
。您可以使用split()
将字符串拆分为单词,并对每隔一个单词调用upper()
,然后使用join()
将字符串重新连接在一起avwztpqn3#
afdcj2ne4#
这不是最紧凑的函数,但它可以做到这一点。
sqserrrh5#
使用regex处理任何非字母数字字符的另一种方法。
输出量:
vc6uscn96#