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
# Python 3 code to demonstrate
# Alternate String to Integer Conversion
# using naive method
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ("Original list is : " + str(test_list))
# using naive method to
# perform conversion
for i in range(0, len(test_list)):
if i % 2:
test_list[i] = int(test_list[i])
# Printing modified list
print ("Modified list is : " + str(test_list))
OutputOriginal 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
# Python 3 code to demonstrate
# Alternate String to Integer Conversion
# using list comprehension
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ("Original list is : " + str(test_list))
# using list comprehension to
# perform conversion
test_list = [int(ele) if idx % 2 else ele for idx, ele in enumerate(test_list)]
# Printing modified list
print ("Modified list is : " + str(test_list))
OutputOriginal 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
# Python 3 code to demonstrate
# Alternate String to Integer Conversion
# using map() function
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ('Original list is :' + str(test_list))
# using map() function to
# perform conversion
test_list[1::2] = list(map(int,test_list[1::2]))
# Printing modified list
print ('Modified list is : ' + str(test_list))
OutputOriginal 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']
#Printing original list
print ('Original list is :' + str(test_list))
#using zip() function to alternate the elements
test_list = [x if i%2==0 else int(x) for i,x in zip(range(len(test_list)),test_list)]
#Printing modified list
print ('Modified list is : ' + str(test_list))
#This code is contributed by Edula Vinay Kumar Reddy
OutputOriginal 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
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print("Original list is : " + str(test_list))
# using enumerate()
# perform conversion
for i, ele in enumerate(test_list):
if i % 2 == 0:
continue
test_list[i] = int(ele)
# Printing modified list
print("Modified list is : " + str(test_list))
#This code is contributed by Vinay Pinjala.
OutputOriginal 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
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print("Original list is : " + str(test_list))
# using for loop with range()
# perform conversion
for i in range(1, len(test_list), 2):
test_list[i] = int(test_list[i])
# Printing modified list
print("Modified list is : " + str(test_list))
OutputOriginal 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
6 min read
Reverse Alternate Characters in a String - Python
Reversing alternate characters in a string involves rearranging the characters so that every second character is reversed while maintaining the original order of other characters. For example, given the string 'abcde', reversing the alternate characters results in 'ebcda', where the first, third and
3 min read
Count the number of characters in a String - Python
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() is
2 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+4F60
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 converted
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
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. Pythons = "1 2 3 4 5" # Convert the string to a list of integers u
2 min read
Python - Convert Binary tuple to Integer
Given Binary Tuple representing binary representation of a number, convert to integer. Input : test_tup = (1, 1, 0) Output : 6 Explanation : 4 + 2 = 6. Input : test_tup = (1, 1, 1) Output : 7 Explanation : 4 + 2 + 1 = 7. Method #1 : Using join() + list comprehension + int() In this, we concatenate t
5 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