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

问题描述

这是我的代码,我在列表中的特定字母前后尝试大写字母。前后任意字母大写 大写首都城市中每个“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','vadUz']

解决方法

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

'/api/getnews/home/post/' + title
,

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

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

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

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

伪代码

  1. 遍历列表并过滤包含“z”的字符串的列表。
[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','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']

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...