Python | Get positional characters from String
Last Updated :
23 Apr, 2023
Sometimes, while working with Python strings, we can have a problem in which we need to create a substring by joining the particular index elements from a string. Let's discuss certain ways in which this task can be performed.
Method #1: Using loop This is a brute method in which this task can be performed. In this, we run a loop over the indices list and join the corresponding index characters from string.
Python3
# 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)
Output : The original string is : gfgisbest
Substring of selective characters : fisbs
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using generator expression + enumerate() The combination of above functionalities can be used to perform this task. In this, we run a loop using generator expression and indices extraction is done with help of enumerate().
Python3
# 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)
Output : The original string is : gfgisbest
Substring of selective characters : fisbs
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using for loop
Python3
# 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 i in range(0, len(test_str)):
if i in indx_list:
res += test_str[i]
# printing result
print("Substring of selective characters : " + res)
OutputThe original string is : gfgisbest
Substring of selective characters : fisbs
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using for list comprehension
Python3
# Python3 code to demonstrate working of
# Get positional characters from String
# 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]
# printing result
print("Substring of selective characters : ", end=' ')
resultstring = ""
reslist = [resultstring+test_str[i] for i in indx_list]
print(''.join(reslist))
OutputThe original string is : gfgisbest
Substring of selective characters : fisbs
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #5: Using map() and lambda function
This method uses the map() function and a lambda function to extract the characters at the specified indices and join them to create the substring.
Python3
# Python3 code to demonstrate working of
# Get positional characters from String
# using map() and lambda function
# 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 map() and lambda function
res = ''.join(list(map(lambda x: test_str[x], indx_list)))
# printing result
print("Substring of selective characters : " + res)
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original string is : gfgisbest
Substring of selective characters : fisbs
Time Complexity: O(n) where n is the number of elements in the index list
Auxiliary Space: O(n) as it uses a list to store the characters at the specified indices.
Method 6 : using the reduce() function from the functools module.
step by step:
- Import the reduce() function from the functools module.
- Initialize the test_str and indx_list variables as before.
- Define a lambda function that takes two arguments: a string and an index. The lambda function returns
- the concatenation of the string with the character at the given index.
- Use the reduce() function to apply the lambda function to each element of the indx_list, starting with an empty string.
- Print the result:
Python3
from functools import reduce
# initializing string
test_str = "gfgisbest"
# initializing index list
indx_list = [1, 3, 4, 5, 7]
# define lambda function
f = lambda x, i: x + test_str[i]
# apply lambda function using reduce
res = reduce(f, indx_list, "")
# printing result
print("Substring of selective characters : " + res)
OutputSubstring of selective characters : fisbs
The time complexity of this approach is O(n), where n is the length of the indx_list.
The auxiliary space complexity is O(1), as we are not using any extra space other than the input and output variables.
Similar Reads
Find position of a character in given string - Python Given a string and a character, our task is to find the first position of the occurrence of the character in the string using Python. For example, consider a string s = "Geeks" and character k = 'e', in the string s, the first occurrence of the character 'e' is at index1. Let's look at various metho
2 min read
Get Last N characters of a string - Python We are given a string and our task is to extract the last N characters from it. For example, if we have a string s = "geeks" and n = 2, then the output will be "ks". Let's explore the most efficient methods to achieve this in Python.Using String Slicing String slicing is the fastest and most straigh
2 min read
Python | Lowercase first character of String The problem of capitalizing a string is quite common and has been discussed many times. But sometimes, we might have a problem like this in which we need to convert the first character of the string to lowercase. Let us discuss certain ways in which this can be performed. Method #1: Using string sli
4 min read
Iterate over characters of a string in Python In this article, we will learn how to iterate over the characters of a string in Python. There are several methods to do this, but we will focus on the most efficient one. The simplest way is to use a loop. Letâs explore this approach.Using for loopThe simplest way to iterate over the characters in
2 min read
Split String into List of characters in Python We are given a string and our task is to split this string into a list of its individual characters, this can happen when we want to analyze or manipulate each character separately. For example, if we have a string like this: 'gfg' then the output will be ['g', 'f', 'g'].Using ListThe simplest way t
2 min read
Python - Lowercase Kth Character in string The problem of lowercasing a string is quite common and has been discussed many times. But sometimes, we might have a problem like this in which we need to convert the Nth character of string to lowercase. Letâs discuss certain ways in which this can be performed. Method #1 : Using string slicing +
4 min read
Python | First character occurrence from rear String There are many ways to find out the first index of element in String as python in its language provides index() function that returns the index of first occurrence of element in String. But if one desires to get the last occurrence of element in string, usually a longer method has to be applied. Let
4 min read
Python - Characters Index occurrences in String Sometimes, while working with Python Strings, we can have a problem in which we need to check for all the characters indices. The position where they occur. This kind of application can come in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using set() + reg
6 min read
Python - Extract range characters from String Given a String, extract characters only which lie between given letters. Input : test_str = 'geekforgeeks is best', strt, end = "g", "s" Output : gkorgksiss Explanation : All characters after g and before s are retained. Input : test_str = 'geekforgeeks is best', strt, end = "g", "r" Output : gkorgk
4 min read
Python | K Character Split String The problems and at the same time applications of list splitting is quite common while working with python strings. Some characters are usually tend to ignore in the use cases. But sometimes, we might not need to omit those characters but include them in our programming output. Letâs discuss certain
4 min read