gpt4 book ai didi

Python:循环和字符串

转载 作者:太空宇宙 更新时间:2023-11-03 15:44:36 24 4
gpt4 key购买 nike

Given two strings s1 and s2 of same length.

Create a new string consisting of the last character of s1 followed by the last character of s2, followed by the second to last character of s1, followed by the second to last character of s2, and so on (in other words the new string should consist of alternating characters of the reverse of s1 and s2).

For example,

if s1="hello" and s2="world", then s3 should be "odlllreohw".

我已经尝试过这个:

s3 = '' 
for i in range(0, min(len(s1), len(s2))):
s3 = s3 + s1[i] + s2[i]

但我不知道如何让它反转 s1 和 s2 中的字母。

最佳答案

在Python中,您可以通过使用负值从末尾偏移来访问字符串或列表。例如:

s3 = s3 + s1[-1] + s2[-2]

将检索 s1 的最后一个字符和 s2 的倒数第二个字符。

关于Python:循环和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41865386/

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