将 Python 列表中字符串中第 N 个字符之前和之后的字符大写

Capitalize a character Before and After Nth character in a string in a Python list

这是我的代码,我在列表中的特定字母前后尝试使用大写字母。前后任意字母大写 首都城市中每个“z”前后的前一个和下一个字母大写。所有其他字母均为小写。包含该字母的所有城市都将存储在列表中并返回。如果我能得到一些意见,那就太好了。另外,如果我需要完全更改代码,请让我知道其他方法。我对此很陌生,如有任何意见,我们将不胜感激。谢谢

lst = ['brazzaville', 'zagreb', 'vaduz']

lst2 = []
for wrd in lst:
    newwrd = ''
    for ltr in wrd:
        if ltr in 'ua':
            newwrd += ltr.capitalize()
        else:
            newwrd += ltr

    lst2.append(newwrd)
print(lst2)

我一直收到这个:

['brAzzAville', 'zAgreb', 'vAdUz']

但我需要这个:

['brAzzAville', 'zAgreb', 'vadUz']

我认为这段代码给出了正确答案,验证一次

def findOccurrences(s, ch):
    return [i for i, letter in enumerate(s) if letter == ch]


lst = ['brazzaville', 'zagreb', 'vaduz']

lst2 = []
result = []
for wrd in lst:
    newwrd = ''
    result = findOccurrences(wrd, 'z')
    for i in range(len(wrd)):
        if (i + 1 in result or i - 1 in result) and wrd[i] != 'z':
            newwrd += wrd[i].capitalize()
        else:
            newwrd += wrd[i]

    lst2.append(newwrd)
print(lst2)

以下策略包括迭代单词并将 z 的 index-1 和 index+1 处的字母(如果存在)替换为大写字母:

lst2 = []
for wrd in lst:
    wrd = wrd.lower()
    for idx, letter in enumerate(wrd):
        if letter == 'z':
            if idx-1 > 0 and wrd[idx - 1] != 'z':
                wrd = wrd.replace(wrd[idx - 1], wrd[idx - 1].upper())
            if idx+1 < len(wrd) and wrd[idx + 1] != 'z':
                wrd = wrd.replace(wrd[idx + 1], wrd[idx + 1].upper())
    if "z" in wrd:
        lst2.append(wrd)

print(lst2)
#['brAzzAville', 'zAgreb', 'vadUz']

将字符串中的第 N 个字符大写

res = lambda test_str,N: test_str[:N] + test_str[N].upper() + test_str[N + 1:] if test_str else ''

伪代码

  1. 遍历列表并过滤列表中包含 'z'.
  2. 的字符串
[check(i) for i in lst if 'z' in i]
  • 对于列表中的每一项:
  1. 找到索引并将前面的字符大写到 'z' 的第一个出现而不旋转。
preind = list(i).index('z')-1 if list(i).index('z')-1>0 else None
k =  res(stri,preind) if(preind) else i
  1. 找到索引并将后续字符大写到 'z' 的最后一次出现而不旋转。
postind = i.rfind('z')+1 if i.rfind('z')+1<len(i) else None
stri =  res(i,preind) if(preind) else stri

代码

lst = ['brazzaville', 'zagreb', 'vaduz']

def check(i):
    stri = ""
    k = ""
    i = i.lower()
    
    # lambda expression to capitalise Nth character in a string 
    res = lambda test_str,N: test_str[:N] + test_str[N].upper() + test_str[N + 1:] if test_str else ''
    
    # find index of the preceeding character to 'z'
    preind = list(i).index('z')-1 if list(i).index('z')-1>0 else None
    
    # find index of the succeeding character to 'z'
    postind = i.rfind('z')+1 if i.rfind('z')+1<len(i) else None
    
    # capitalise preceeding character to 'z'
    stri =  res(i,preind) if(preind) else i
    # capitalise succeeding character to 'z'
    k = res(stri,postind) if(postind) else stri

    # return the processed string 
    return k
    
    

print([check(i) for i in lst if 'z' in i ])
#output
['brAzzAville', 'zAgreb', 'vadUz']