You are currently viewing Convert String to Tuple Python

How to convert a string to a tuple in Python? You can convert a string to a tuple using different approaches of Python, you can use the split() method to split the string into a list of individual elements, and then use the tuple() function to convert the resulting list into a tuple.

Advertisements

In this article, I will explain different approaches of Python to convert a string to a tuple such as split(), map(), int(), eval(), reduce(), heapq, regular expression module, list comprehension, and split() & tuple() functions.

1. Quick Examples of Converting a String to a Tuple

If you are in a hurry, below are some quick examples of converting a string to a tuple.


# Quick examples of converting a string to a tuple

# Initialize string
string = "2, 6, 9, -4, 3"

# Example 1: Split string and convert to tuple
string = "Welcom to Sparkbyexample .com"
result = tuple(string.split(", "))

# Example 2: Using split() method
# to convert string to tuple
result = tuple(string.split(", "))

# Example 3: Convert string to tuple 
# Using map(), int(), split()
result = tuple(map(int, string.split(", ")))

# Example 4: Convert string to tuple 
# Using eval()
result = eval("(" + string + ")")

# Example 5: Convert string to tuple 
# Using reduce() function
result = reduce(lambda acc, num: acc + (int(num),), string.split(", "), ())

# Example 6: Using heapq method convert string to tuple
str_list = string.split(', ')
int_list = [int(i) for i in str_list]
result = tuple(int_list)

# Example 7: Using the regular expression module
# convert string to tuple
string_list = re.split(', ', string)
int_list = []
for str_ in string_list:
    int_list.append(int(str_))
result = tuple(int_list)

# Example 8: Using split and list comprehension
str_list = string.split(", ")
result = [int(i) for i in str_list]

2. Convert String to Tuple Using split() Function

You can use the built-in split() function to split the string into a list of substrings and then use a tuple() function to convert the resultant list into a tuple.

split() function splits the string over the specified delimiter. It takes two optional arguments: First, sep, which is a string delimiter that separates the substrings (defaults to white space), and second, maxsplit which is an integer that specifies the maximum number of splits to perform.

Apply the split() function to the given string by default, it splits the string at white space and returns a list of substrings. Then you can use the tuple() function to convert a list of substrings into a tuple.


# Initialize string
string = "Welcome to Sparkbyexample .com"
print("Original String:", string)

# Split string and convert to tuple
result = tuple(string.split())
print("After converting the string to a tuple:", result)

Yields below output.

python string to tuple

Let’s take another example of converting a string to a tuple.


# Initialize string
string = "2, 6, 9, -4, 3"
print("Original String:", string)

# Using split() method & tuple()
# to convert string to tuple
result = tuple(string.split(", "))
print("After converting the string to a tuple:", result)

# Output:
# Original String: 2, 6, 9, -4, 3
# After converting the string to a tuple: ('2', '6', '9', '-4', '3')

3. Convert String to Tuple using map(), int(), & split()

You can use map(), int(), split(), and tuple() to convert the string into a tuple. In this program, the split(", ") method is used to split the string at each comma followed by a space, resulting in a list of substrings. Then, map(int, …) is used to apply the int() function to each substring, converting them into integers. Finally, tuple() is used to create a tuple from the resulting sequence of integers.

Related: In Python, you can also remove numbers from a string.


# Initialize string
string = "2, 6, 9, -4, 3"
print("Original String: ", string)

# Convert string to tuple 
# Using map(), int(), split()
result = tuple(map(int, string.split(", ")))
print("After converting the string to a tuple:", result)

Yields below output.

python string to tuple

4. Convert Python String to Tuple Without Split

To convert the string into a tuple without splitting its elements, you can use the eval() function. For example, you can concatenate the string with parentheses to create a valid tuple expression. Then, you can pass the resulting expression to eval() to evaluate it and convert it into a tuple.

However, I would like to reiterate that using eval() can be risky if the string contains untrusted or unknown content, as it can execute arbitrary code. It is generally recommended to use safer alternatives like split(), int(), and tuple() as mentioned earlier, unless you have complete control over the input string.


# Initialize sring
string = "2, 6, 9, -4, 3"
print("Orginal String: ",string)

# Convert string to tuple 
# Using eval()
result = eval("(" + string + ")")
print("After converting the string to a tuple: ", result)

# Using eval() function
result = eval(string)
print("After converting string to Tuple: ",result)

Yields the same output as above.

5. Convert String to Tuple using the reduce() Function

To convert a string to a tuple use the reduce() function. In the below code, you can import the reduce() function from the functools module. This function applies a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value.

You can use a lambda function as the reducing function. The lambda function takes two arguments, acc and num, where acc accumulates the result and num represents each number in the string after splitting it using split(", "). The lambda function converts num to an integer using int(num) and appends it to the accumulated result acc using tuple concatenation (int(num),).


from functools import reduce

# Initialize string
string = "2, 6, 9, -4, 3"
print("Original String: ", string)

# Convert string to tuple 
# Using reduce() function
result = reduce(lambda acc, num: acc + (int(num),), string.split(", "), ())
print("After converting the string to a tuple: ", result)

Yields the same output as above.

6. Using heapq Method

Alternatively, you can use the heapq method to convert the string to a tuple. For example, you can split the string into a list of substrings using string.split(', '). Then, you can iterate over each substring using a list comprehension to convert them to integers. The resulting list of integers is then converted to a tuple using a tuple() function.


import heapq

# Initialize string
string = "2, 6, 9, -4, 3"
print("Original String: ", string)

# Using the heapq method
# to convert string to a tuple
str_list = string.split(', ')
int_list = [int(i) for i in str_list]
result = tuple(int_list)
print("After converting the string to a tuple: ", result)

Yields the same output as above.

7. Using the Regular Expression Module

Similarly, you can convert the string to a tuple using the re module for splitting and converting the substrings to integers. For instance, the re.split(', ', string) function is used to split the string at each comma followed by a space, resulting in a list of substrings. Then, a for loop is used to iterate over each substring and convert it to an integer using int(str_). The integers are appended to the int_list, and finally, tuple(int_list) is used to create a tuple from the resulting list of integers.


import re

# Initialize string
string = "2, 6, 9, -4, 3"
print("Original String: ", string)

# Using the regular expression module
string_list = re.split(', ', string)
int_list = []
for str_ in string_list:
    int_list.append(int(str_))
result = tuple(int_list)
print("After converting the string to a tuple: ", result)

Yields the same output as above.

8. Using List Comprehension

You can also use list comprehension to convert the string into a tuple. First, You can use the split() function to split the string into a list of substrings and convert it into a list of integers using list comprehension. Finally, you can use the tuple() function to create a tuple from the resulting list.


# Initialize string
string = "2, 6, 9, -4, 3"
print("The original string :", end = ' ')
print(string)

# Using split and list comprehension
str_list = string.split(", ")
result = [int(i) for i in str_list]
print("After converting the string to a tuple:", end = ' ')
print(tuple(result))

Yields the same output as above.

10. Conclusion

In this article, I have explained how to convert a string to a tuple in Python by using split(), map(), int(), eval(), reduce(), heapq, regular expression module, list comprehension, and split() & tuple() functions with examples.

Happy Learning !!