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
test_str = "gfgisbest"
print ( "The original string is : " + test_str)
indx_list = [ 1 , 3 , 4 , 5 , 7 ]
res = ''
for ele in indx_list:
res = res + test_str[ele]
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
test_str = "gfgisbest"
print ( "The original string is : " + test_str)
indx_list = [ 1 , 3 , 4 , 5 , 7 ]
res = ''.join((char for idx, char in enumerate (test_str) if idx in indx_list))
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
test_str = "gfgisbest"
print ( "The original string is : " + test_str)
indx_list = [ 1 , 3 , 4 , 5 , 7 ]
res = ''
for i in range ( 0 , len (test_str)):
if i in indx_list:
res + = test_str[i]
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 #4: Using for list comprehension
Python3
test_str = "gfgisbest"
print ( "The original string is : " + test_str)
indx_list = [ 1 , 3 , 4 , 5 , 7 ]
print ( "Substring of selective characters : " , end = ' ' )
resultstring = ""
reslist = [resultstring + test_str[i] for i in indx_list]
print (''.join(reslist))
|
Output
The 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
test_str = "gfgisbest"
print ( "The original string is : " + test_str)
indx_list = [ 1 , 3 , 4 , 5 , 7 ]
res = ''.join( list ( map ( lambda x: test_str[x], indx_list)))
print ( "Substring of selective characters : " + res)
|
Output
The 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
test_str = "gfgisbest"
indx_list = [ 1 , 3 , 4 , 5 , 7 ]
f = lambda x, i: x + test_str[i]
res = reduce (f, indx_list, "")
print ( "Substring of selective characters : " + res)
|
Output
Substring 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
Python | Find position of a character in given string
Given a string and a character, your task is to find the first position of the character in the string using Python. These types of problems are very competitive programming where you need to locate the position of the character in a string. Let's discuss a few methods to solve the problem. Method 1
4 min read
Python - Extract only characters from given string
To extract only characters (letters) from a given string we can use various easy and efficient methods in Python. Using str.isalpha() in a Loop str.isalpha() method checks if a character in a string is an alphabetic letter. Using a loop, we can iterate through each character in a string to filter ou
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 straig
2 min read
Python - Least Frequent Character in String
The task is to find the least frequent character in a string, we count how many times each character appears and pick the one with the lowest count. Using collections.CounterThe most efficient way to do this is by using collections.Counter which counts character frequencies in one go and makes it ea
3 min read
Remove Multiple Characters from a String in Python
Removing multiple characters from a string in Python can be achieved using various methods, such as str.replace(), regular expressions, or list comprehensions. Each method serves a specific use case, and the choice depends on your requirements. Letâs explore the different ways to achieve this in det
3 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
Python - Check if string contains character
In Python, we can check if a string contains a character using several methods. in operator is the simplest and most commonly used way. If we need more control, methods like find(), index(), and count() can also be useful. Using in Operator in operator is the easiest way to check if a character exis
2 min read
Python program to remove last N characters from a string
In this article, weâll explore different ways to remove the last N characters from a string in Python. This common string manipulation task can be achieved using slicing, loops, or built-in methods for efficient and flexible solutions. Using String SlicingString slicing is one of the simplest and mo
2 min read
Remove Special Characters from String in Python
When working with text data in Python, it's common to encounter strings containing unwanted special characters such as punctuation, symbols or other non-alphanumeric elements. For example, given the input "Data!@Science#Rocks123", the desired output is "DataScienceRocks123". Let's explore different
2 min read
Python - Maximum frequency character in String
The task of finding the maximum frequency character in a string involves identifying the character that appears the most number of times. For example, in the string "hello world", the character 'l' appears the most frequently (3 times). Using collection.CounterCounter class from the collections modu
3 min read