2017-07-27 49 views
0

我刚开始学习Python,因此请耐心等待。我的数学知识也有点不稳定。我能够将一个单词或字符串中的第一个单词大写。我遇到的问题是我需要大写字符串中的每个第三个字母。我需要做这个功能。 我已经使用过类似的东西,但是只能用这个来改变这个字母,而不是每一个字。将字符串中的每个第三个字母都大写 - Python

x = "string" 
y = x[:3] + x[3].swapcase() + x[4:] 

还有就是使用

if i in phrase (len(phrase)) 

的样本模板,但我不相信是如何工作的。

我想输出显示类似“这个短信功能”

预先感谢任何帮助。

+1

如何处理字符串中的空格?他们忽略或跳过? – 101

+1

您的预期结果不一致 - 直到'fuNctIon'似乎忽略空格,但如果它忽略空格,它应该是'FunCtiOn'。 – zwer

+0

@zwer操作非常清晰:“我需要将字符串中的每个第三个字母大写”。请不要提出OP未提及的新要求! – alfasin

回答

0

尝试应用一些splitlambda,然后再按join

>>> x = "this texting function" 
>>> " ".join(map(lambda w: w[:2] + w[2].swapcase() + w[3:], x.split())) 
'thIs teXting fuNction' 

如果你不是拉姆达的粉丝,那么你可以这样写

>>> def swapcase_3rd(string): 
...  if len(string) >3: 
...    return string[:2] + string[2].swapcase() + string[3:] 
...  if len(string) == 3: 
...    return string[:2] + string[2].swapcase() 
...  return string 
... 
>>> x = "this texting function" 
>>> " ".join(map(swapcase_3rd, x.split())) 
'thIs teXting fuNction' 
0

的方法如果你不关心字母和空格:

''.join(phrase[i-1] if i % 3 or i == 0 else phrase[i-1].upper() for i in range(1, len(phrase) + 1)) 

如果你只想计算字母:

new_phrase = '' 
phrase = "here are some words" 
counter = 0 
for c in phrase: 
    if not c.isalpha(): 
     new_phrase += c 
    else: 
     counter += 1 
     if not counter % 3: 
      new_phrase += c.upper() 
     else: 
      new_phrase += c 

由于您的示例显示您使用swapcase()而不是upper(),因此只需在此代码中将upper()替换为swapcase()以实现该功能(如果这是您想要的)。

0
x = "string" 
z = list(x) 
for x in range(2,len(z),3): # start from 3rd (index2) and step by 3 
    z[x] = z[x].upper() 
x = ''.join(z) 
print x 

输出:串

0

既然你想第三个字母,而不仅仅是第三个字母,我们需要根据字符的位置重复的字母和产生的结果是:

def cap_3rd(word): 
    result = "" 
    for i in range(1, len(word) + 1): 
     if i % 3 == 0: 
      result += word[i-1].upper() 
     else: 
      result += word[i-1] 
    return result 


word = "thisisaverylonglongword" 
print(cap_3rd(word)) # thIsiSavEryLonGloNgwOrd 
1

你可以把一个数组,使一个漂亮和Python的几行字的步幅片:

s = "thisisareallylongstringwithlotsofletters" 

# convert to list 
a = list(s) 

#change every third letter in place with a list comprehension 
a[2::3] = [x.upper() for x in a[2::3]] 

#back to a string 
s = ''.join(a) 

# result: thIsiSarEalLylOngStrIngWitHloTsoFleTteRs 

目前还不清楚你想要什么空间 - 这将它们当作人物来对待。

相关问题