Python程序打印k个字符然后跳过字符串中的k个字符
给定一个字符串,交替提取 K 个字符。
Input : test_str = ‘geeksgeeksisbestforgeeks’, K = 4
Output : geekksisforg
Explanation : Every 4th alternate range is sliced.
Input : test_str = ‘geeksgeeksisbest’, K = 4
Output : geekksis
Explanation : Every 4th alternate range is sliced.
方法#1:使用循环+切片
在此,我们使用切片执行获取 K 个字符的任务,并使用循环执行连接任务。
Python3
# Python3 code to demonstrate working of
# Alternate K Length characters
# Using loop + slicing
# initializing string
test_str = 'geeksgeeksisbestforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
res = ''
# skipping k * 2 for altering effect
for idx in range(0, len(test_str), K * 2):
# concatenating K chars
res += test_str[idx : idx + K]
# printing result
print("Transformed String : " + str(res))
Python3
# Python3 code to demonstrate working of
# Alternate K Length characters
# Using list comprehension + join()
# initializing string
test_str = 'geeksgeeksisbestforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
# slicing K using slicing, join for converting back to string
res = ''.join([test_str[idx : idx + K] for idx in range(0, len(test_str), K * 2)])
# printing result
print("Transformed String : " + str(res))
输出:
The original string is : geeksgeeksisbestforgeeks
Transformed String : geekksisforg
方法 #2:使用列表理解 + join()
这类似于上面的方式,唯一的区别是它的一种线性方法,并且 join() 用于执行转换回字符串的任务。
蟒蛇3
# Python3 code to demonstrate working of
# Alternate K Length characters
# Using list comprehension + join()
# initializing string
test_str = 'geeksgeeksisbestforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
# slicing K using slicing, join for converting back to string
res = ''.join([test_str[idx : idx + K] for idx in range(0, len(test_str), K * 2)])
# printing result
print("Transformed String : " + str(res))
输出:
The original string is : geeksgeeksisbestforgeeks
Transformed String : geekksisforg