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
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
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
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
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
Python - Convert Tuple String to Integer Tuple Interconversion of data is a popular problem developer generally deal with. One can face a problem to convert tuple string to integer tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be
7 min read
Python - Check if String contains any Number We are given a string and our task is to check whether it contains any numeric digits (0-9). For example, consider the following string: s = "Hello123" since it contains digits (1, 2, 3), the output should be True while on the other hand, for s = "HelloWorld" since it has no digits the output should
2 min read
Python - Test if Kth character is digit in String Given a String, check if Kth index is a digit. Input : test_str = 'geeks9geeks', K = 5 Output : True Explanation : 5th idx element is 9, a digit, hence True.Input : test_str = 'geeks9geeks', K = 4 Output : False Explanation : 4th idx element is s, not a digit, hence False. Method #1: Using in operat
5 min read
Python - Extract String till Numeric Given a string, extract all its content till first appearance of numeric character. Input : test_str = "geeksforgeeks7 is best" Output : geeksforgeeks Explanation : All characters before 7 are extracted. Input : test_str = "2geeksforgeeks7 is best" Output : "" Explanation : No character extracted as
5 min read