Python程序反转字符串中的替代字符
给定一个 String ,反转它的替代字符字符串。
Input : test_str = ‘geeks4rgeeks’
Output : keekr4sgeegs
Explanation : only g, e, s, r, e, k are reversed, rest all have same position.
Input : test_str = ‘geeks’
Output : seekg
Explanation : only g, e, s are reversed, rest all have same position.
方法 #1:使用循环 + 切片 + reversed()
这是可以执行此任务的方法之一。在这种情况下,我们使用切片提取交替,然后使用 reversed 反转字符串。字符串的重建是使用循环完成的。
Python3
# Python3 code to demonstrate working of
# Alternate characters reverse in String
# Using loop + slicing + reversed()
# initializing string
test_str = 'geeks4rgeeks'
# printing original string
print("The original string is : " + str(test_str))
# extracting alternate string
alt = test_str[::2]
not_alt = test_str[1::2]
# performing reverse
alt = "".join(reversed(alt))
res = ''
# remaking string
for idx in range(len(alt)):
res += alt[idx]
res += not_alt[idx]
# printing result
print("Is alternate reversed string : " + str(res))
Python3
# Python3 code to demonstrate working of
# Alternate characters reverse in String
# Using list comprehension
# initializing string
test_str = 'geeks4rgeeks'
# printing original string
print("The original string is : " + str(test_str))
# using one-liner to solve the problem
res = "".join(["".join(reversed(test_str[::2]))[idx] + test_str[1::2][idx]
for idx in range(len("".join(reversed(test_str[::2]))))])
# printing result
print("Is alternate reversed string : " + str(res))
输出
The original string is : geeks4rgeeks
Is alternate reversed string : keekr4sgeegs
方法#2:使用列表理解
这是可以执行此任务的另一种方式。在这方面,我们通过使用列表理解的单行功能来执行与上述类似的函数。
蟒蛇3
# Python3 code to demonstrate working of
# Alternate characters reverse in String
# Using list comprehension
# initializing string
test_str = 'geeks4rgeeks'
# printing original string
print("The original string is : " + str(test_str))
# using one-liner to solve the problem
res = "".join(["".join(reversed(test_str[::2]))[idx] + test_str[1::2][idx]
for idx in range(len("".join(reversed(test_str[::2]))))])
# printing result
print("Is alternate reversed string : " + str(res))
输出
The original string is : geeks4rgeeks
Is alternate reversed string : keekr4sgeegs