📜  Python程序连接字符串的第K个索引词

📅  最后修改于: 2022-05-13 01:55:02.438000             🧑  作者: Mango

Python程序连接字符串的第K个索引词

给定一个包含单词的字符串,连接每个单词的第 K 个索引。

方法 #1:使用 join() + 列表理解 + split()

在此,我们执行拆分任务以获取所有单词,然后使用列表推导获取单词的所有第 K 个索引,join() 用于执行连接。

Python3
# initializing string
test_str = 'geeksforgeeks best for geeks'
  
# printing original string
print("The original string is : " + test_str)
  
# initializing K 
K = 2
  
# joining Kth index of each word
res = ''.join([sub[K] for sub in test_str.split()])
      
# printing result 
print("The K joined String is : " + str(res))


Python3
# initializing string
test_str = 'geeksforgeeks best for geeks'
  
# printing original string
print("The original string is : " + test_str)
  
# initializing K 
K = 2
  
# getting Kth element of each word
temp = []
for sub in test_str.split():
  temp.append(sub[K])
  
# joining together  
res = ''.join(temp)
      
# printing result 
print("The K joined String is : " + str(res))


输出:

The original string is : geeksforgeeks best for geeks
The K joined String is : esre

方法 #2:使用循环 + join()

在此,我们执行以暴力方式使用循环获取第 K 个索引元素的任务,然后使用 join() 进行连接。

Python3

# initializing string
test_str = 'geeksforgeeks best for geeks'
  
# printing original string
print("The original string is : " + test_str)
  
# initializing K 
K = 2
  
# getting Kth element of each word
temp = []
for sub in test_str.split():
  temp.append(sub[K])
  
# joining together  
res = ''.join(temp)
      
# printing result 
print("The K joined String is : " + str(res))

输出:

The original string is : geeksforgeeks best for geeks
The K joined String is : esre