如何在python中将字符串中的每隔一个单词大写

wooyq4lh  于 2022-11-21  发布在  Python
关注(0)|答案(6)|浏览(190)

我想知道如何将字符串中的每一个单词都大写。例如,我想将“Here is my dog”改为“Here is my DOG”。有人能帮我开始吗?我所能找到的就是如何将每个单词的第一个字母大写。

bgtovc5b

bgtovc5b1#

' '.join( w.upper() if i%2 else w
          for (i, w) in enumerate(sentence.split(' ')) )
nfg76nw0

nfg76nw02#

我认为您要寻找的方法是upper()。您可以使用split()将字符串拆分为单词,并对每隔一个单词调用upper(),然后使用join()将字符串重新连接在一起

avwztpqn

avwztpqn3#

words = sentence.split(' ')
sentence = ' '.join(sum(zip(words[::2], map(str.upper, words[1::2])), ()))
afdcj2ne

afdcj2ne4#

这不是最紧凑的函数,但它可以做到这一点。

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)
sqserrrh

sqserrrh5#

使用regex处理任何非字母数字字符的另一种方法。

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.
vc6uscn9

vc6uscn96#

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)

相关问题