如何在python中使用字符串中的每个其他单词大写

时间:2011-12-09 22:39:50

标签: python

我想知道如何在字符串中大写每个其他单词。例如,我想把“这是我的狗”改为“这是我的狗” 任何人都可以帮助我开始吗?我能找到的就是如何将每个单词中的第一个字母大写。

5 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:2)

我认为您正在寻找的方法是upper()。 您可以使用split()将字符串拆分为单词,并在每个其他单词上调用upper(),然后使用join()

将字符串重新连接在一起

答案 2 :(得分:1)

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

答案 3 :(得分:0)

这不是最紧凑的功能,但这可以解决问题。

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)

答案 4 :(得分:0)

使用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.