gpt4 book ai didi

python - 改变字符串中某些字符大小写的函数

转载 作者:太空宇宙 更新时间:2023-11-04 01:53:05 25 4
gpt4 key购买 nike

我有一个字符串,我想将第一个字母和每个备用字母更改为大写,并且还利用列表理解来转换我的嵌套 for 循环。

我有字符串,我设法将它拆分成单词并使用嵌套的 for 循环,将字母进行必要的大写转换,但我无法从嵌套的 for 循环中将结果捕获到正确的数组中而且我也无法用列表理解替换嵌套的 for 循环。

输入字符串

st = 'This is my expected function that is supposed to convert the first character and every alternate character into upper case'

将输入的字符串转换为单词

words = [b for b in st.split()]

for i in range(0,len(words)):
temp_word = list(words[i])
for j in range(0,len(temp_word),2):
temp_word[j] = temp_word[j].upper()
print(temp_word)

输入:'这是我预期的函数,应该转换第一个字符和每个替代字符转换为大写'

输出:“这是我预期的函数,它被支持将第一个字符和每个备用字符转换为大写”

最佳答案

你可以用列表理解来做一个join:

' '.join([''.join([char.upper() if i % 2 == 0 else char for i, char in enumerate(word)]) for word in st.split()])

示例:

st = 'This is my expected function that is supposed to convert the first character and every alternate character into upper case'

print(' '.join([''.join([char.upper() if i % 2 == 0 else char for i, char in enumerate(word)]) for word in st.split()]))
# ThIs Is My ExPeCtEd FuNcTiOn ThAt Is SuPpOsEd To CoNvErT ThE FiRsT ChArAcTeR AnD EvErY AlTeRnAtE ChArAcTeR InTo UpPeR CaSe

关于python - 改变字符串中某些字符大小写的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57546089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com