📌  相关文章
📜  Python|从字符串中获取位置字符

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

Python|从字符串中获取位置字符

有时,在使用Python字符串时,我们可能会遇到需要通过连接字符串中的特定索引元素来创建子字符串的问题。让我们讨论可以执行此任务的某些方式。

方法#1:使用循环
这是可以执行此任务的蛮力方法。在此,我们在索引列表上运行一个循环,并从字符串连接相应的索引字符。

# Python3 code to demonstrate working of
# Get positional characters from String
# using loop
  
# initializing string 
test_str = "gfgisbest"
  
# printing original string 
print("The original string is : " + test_str)
  
# initializing index list 
indx_list = [1, 3, 4, 5, 7]
  
# Get positional characters from String
# using loop
res = ''
for ele in indx_list:
    res = res + test_str[ele]
  
# printing result
print("Substring of selective characters : " + res)
输出 :
The original string is : gfgisbest
Substring of selective characters : fisbs

方法 #2:使用生成器表达式 + enumerate()
上述功能的组合可用于执行此任务。在此,我们使用生成器表达式运行一个循环,并在 enumerate() 的帮助下完成索引提取。

# Python3 code to demonstrate working of
# Get positional characters from String
# using generator expression + enumerate()
  
# initializing string 
test_str = "gfgisbest"
  
# printing original string 
print("The original string is : " + test_str)
  
# initializing index list 
indx_list = [1, 3, 4, 5, 7]
  
# Get positional characters from String
# using generator expression + enumerate()
res = ''.join((char for idx, char in enumerate(test_str) if idx in indx_list))
  
# printing result
print("Substring of selective characters : " + res)
输出 :
The original string is : gfgisbest
Substring of selective characters : fisbs