Python – Convert Alternate String Character to Integer
Last Updated :
13 Apr, 2023
Interconversion between data types is facilitated by python libraries quite easily. But the problem of converting the alternate list of string to integers is quite common in development domain. Let’s discuss few ways to solve this particular problem.
Method #1 : Naive Method This is most generic method that strikes any programmer while performing this kind of operation. Just looping over whole list and convert alternate of the string of list to int by type casting.
Python3
test_list = [ '1' , '4' , '3' , '6' , '7' ]
print ( "Original list is : " + str (test_list))
for i in range ( 0 , len (test_list)):
if i % 2 :
test_list[i] = int (test_list[i])
print ( "Modified list is : " + str (test_list))
|
Output
Original list is : ['1', '4', '3', '6', '7']
Modified list is : ['1', 4, '3', 6, '7']
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list
Method #2 : Using list comprehension This is just a kind of replica of the above method, just implemented using list comprehension, kind of shorthand that a developer looks for always. It saves time and complexity of coding a solution.
Python3
test_list = [ '1' , '4' , '3' , '6' , '7' ]
print ( "Original list is : " + str (test_list))
test_list = [ int (ele) if idx % 2 else ele for idx, ele in enumerate (test_list)]
print ( "Modified list is : " + str (test_list))
|
Output
Original list is : ['1', '4', '3', '6', '7']
Modified list is : ['1', 4, '3', 6, '7']
Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
Method#3:Using map() function:
The map() function to apply the int() function to every other element of the list using slicing, effectively converting every other element to an integer.
Python3
test_list = [ '1' , '4' , '3' , '6' , '7' ]
print ( 'Original list is :' + str (test_list))
test_list[ 1 :: 2 ] = list ( map ( int ,test_list[ 1 :: 2 ]))
print ( 'Modified list is : ' + str (test_list))
|
Output
Original list is :['1', '4', '3', '6', '7']
Modified list is : ['1', 4, '3', 6, '7']
Time Complexity: O(n) where n is the number of elements in the string list. The map() is used to perform the task and it takes O(n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the test list.
Method#4: Using the zip() function to alternate the elements in the list
Python3
test_list = [ '1' , '4' , '3' , '6' , '7' ]
print ( 'Original list is :' + str (test_list))
test_list = [x if i % 2 = = 0 else int (x) for i,x in zip ( range ( len (test_list)),test_list)]
print ( 'Modified list is : ' + str (test_list))
|
Output
Original list is :['1', '4', '3', '6', '7']
Modified list is : ['1', 4, '3', 6, '7']
Time complexity: O(n) where n is the length of the input list
Auxiliary Space: O(n) as a new list of the same length is created during the conversion.
Method #5: Using enumeration
Algorithm:
- Initialize the input list test_list.
- Print the original list.
- Use enumerate() to iterate over each element of test_list with its index.
- For each element, check whether the index is even or odd.
- If the index is even, skip the element using the continue statement.
- If the index is odd, convert the element to an integer using int() and replace the original element in test_list with the new integer value.
- Print the modified list.
Python3
test_list = [ '1' , '4' , '3' , '6' , '7' ]
print ( "Original list is : " + str (test_list))
for i, ele in enumerate (test_list):
if i % 2 = = 0 :
continue
test_list[i] = int (ele)
print ( "Modified list is : " + str (test_list))
|
Output
Original list is : ['1', '4', '3', '6', '7']
Modified list is : ['1', 4, '3', 6, '7']
Time complexity: O(n), where n is the length of the input list test_list. This is because the for loop and if statement iterate over each element of the list exactly once. The time complexity is proportional to the length of the input list.
Auxiliary Space: O(1), because the code modifies the input list in place without creating any additional data structures. Therefore, the space used by the algorithm is constant and independent of the length of the input list.
Method #6: Using a for loop with a range
This approach uses a for loop with a range to iterate over every other index in the list and convert the corresponding element to an integer.
Python3
test_list = [ '1' , '4' , '3' , '6' , '7' ]
print ( "Original list is : " + str (test_list))
for i in range ( 1 , len (test_list), 2 ):
test_list[i] = int (test_list[i])
print ( "Modified list is : " + str (test_list))
|
Output
Original list is : ['1', '4', '3', '6', '7']
Modified list is : ['1', 4, '3', 6, '7']
Time complexity: O(n), where n is the length of the list.
Auxiliary space: O(1), since we are modifying the original list in-place.
Similar Reads
Python Program for Convert characters of a string to opposite case
Given a string, convert the characters of the string into the opposite case,i.e. if a character is the lower case then convert it into upper case and vice-versa. Examples: Input : geeksForgEeksOutput : GEEKSfORGeEKSInput: hello every oneOutput: HELLO EVERY ONEExample 1: Python Program for Convert ch
7 min read
Reverse Alternate Characters in a String - Python
We have to reverse the alternate characters in a given string. The task is to identify every second character in the string, reverse their order and keep the other characters unchanged. For example, "abcd" needs to be changed to "cbad" and "abcde" needs to be changed to "ebcda" This can be accomplis
4 min read
Python - Convert String to unicode characters
Convert String to Unicode characters means transforming a string into its corresponding Unicode representations. Unicode is a standard for encoding characters, assigning a unique code point to every character. For example: string "A" has the Unicode code point U+0041.string "ä½ å¥½" corresponds to U+4F6
2 min read
Alternate cases in String - Python
The task of alternating the case of characters in a string in Python involves iterating through the string and conditionally modifying the case of each character based on its position. For example, given a string s = "geeksforgeeks", the goal is to change characters at even indices to uppercase and
3 min read
Integer to Binary String in Python
We have an Integer and we need to convert the integer to binary string and print as a result. In this article, we will see how we can convert the integer into binary string using some generally used methods. Example: Input : 77Output : 0b1001101Explanation: Here, we have integer 77 which we converte
4 min read
Python program to count the number of characters in a String
The goal here is to count the number of characters in a string, which involves determining the total length of the string. For example, given a string like "GeeksForGeeks", we want to calculate how many characters it contains. Letâs explore different approaches to accomplish this. Using len()len() i
3 min read
How to Create String Array in Python ?
To create a string array in Python, different methods can be used based on the requirement. A list can store multiple strings easily, NumPy arrays offer more features for large-scale data and the array module provides type-restricted storage. Each method helps in managing collections of text values
2 min read
Convert Complex Number to String in Python
We are given complex numbers and we have to convert these complex numbers into strings and return the result in string form. In this article, we will see how we can convert complex numbers to strings in Python. Examples: Input : 3+4j <complex>Output : 3+4j <string> Explanation: We can se
3 min read
Python - Integers String to Integer List
In this article, we will check How we can Convert an Integer String to an Integer List Using split() and map()Using split() and map() will allow us to split a string into individual elements and then apply a function to each element. [GFGTABS] Python s = "1 2 3 4 5" # Convert the string to
2 min read
Python program to convert a byte string to a list of integers
We have to convert a byte string to a list of integers extracts the byte values (ASCII codes) from the byte string and stores them as integers in a list. For Example, we are having a byte string s=b"Hello" we need to write a program to convert this string to list of integers so the output should be
2 min read