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

如何在python中对字符串中的其他单词使用大写字母,python,Python,我想知道如何在字符串中每隔一个单词用大写字母。例如,我想把这里是我的狗换成这里是我的狗 有人能帮我开始吗?我所能找到的就是如何将每个单词的第一个字母大写 我认为您正在寻找的方法是。 您可以使用将字符串拆分为单词,然后每隔一个单词调用upper,然后使用将字符串重新连接在一起。我认为您正在寻找的方法是。 您可以使用将字符串拆分为单词,然后每隔一个单词调用upper,然后使用将字符串重新连接在一起。这并不是最紧凑的函数,但这样做就可以了 string = "Here is my dog" def

我想知道如何在字符串中每隔一个单词用大写字母。例如,我想把这里是我的狗换成这里是我的狗
有人能帮我开始吗?我所能找到的就是如何将每个单词的第一个字母大写

我认为您正在寻找的方法是。
您可以使用将字符串拆分为单词,然后每隔一个单词调用upper,然后使用

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

将字符串重新连接在一起。这并不是最紧凑的函数,但这样做就可以了

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)

这不是最紧凑的函数,但这会起作用

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.
用于处理任何非字母数字字符的另一种方法

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.

非常感谢,但是你能帮我解释一下for循环吗?Neal Wang a是所有单词的列表,w在a中的意思是:单词列表中每个单词的意思。for循环为wordlista中的每个wordw执行底层代码。可以找到for循环的一个很好的例子。非常感谢,但是你能帮我解释for循环吗?Neal Wang a是所有单词的列表,w在a中的意思是:单词列表中每个单词的意思。for循环为wordlista中的每个wordw执行底层代码。可以找到for循环的一个很好的例子。如果必须同时处理str和unicode,则这不适用于使用unicode输入的python2,因为str.upper.lambda x:x.upper必须同时处理str和unicode。如果必须同时处理str和unicode,则这不适用于使用unicode输入的python2。