Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – To convert a list of strings with a delimiter to a list of tuple
Converting a list of strings with delimiters to a list of tuples is a common task in Python. This can be achieved using list comprehension combined with the split() method to break strings at delimiter positions.
Basic Example
Here's how to convert delimiter-separated strings into tuples of integers ?
data_list = ["33-22", "13-44-81-39", "42-10-42", "36-56-90", "34-77-91"]
print("Original list:")
print(data_list)
delimiter = "-"
result = [tuple(int(element) for element in item.split(delimiter)) for item in data_list]
print("\nConverted to tuples:")
print(result)
Original list: ['33-22', '13-44-81-39', '42-10-42', '36-56-90', '34-77-91'] Converted to tuples: [(33, 22), (13, 44, 81, 39), (42, 10, 42), (36, 56, 90), (34, 77, 91)]
Different Delimiters
The same approach works with various delimiter characters ?
# Using comma delimiter
csv_data = ["10,20,30", "40,50", "60,70,80,90"]
comma_result = [tuple(int(x) for x in item.split(",")) for item in csv_data]
print("Comma-separated result:")
print(comma_result)
# Using pipe delimiter
pipe_data = ["red|green|blue", "yellow|orange"]
pipe_result = [tuple(item.split("|")) for item in pipe_data]
print("\nPipe-separated result:")
print(pipe_result)
Comma-separated result:
[(10, 20, 30), (40, 50), (60, 70, 80, 90)]
Pipe-separated result:
[('red', 'green', 'blue'), ('yellow', 'orange')]
How It Works
The conversion process involves three key steps:
Split:
item.split(delimiter)breaks each string into a list of substringsConvert:
int(element)converts each substring to the desired data typeTuple:
tuple()converts the list of converted elements into a tuple
Handling Mixed Data Types
You can also work with mixed data types by applying different conversions ?
mixed_data = ["John-25-Engineer", "Alice-30-Designer", "Bob-28-Developer"]
def parse_record(record):
parts = record.split("-")
return (parts[0], int(parts[1]), parts[2])
result = [parse_record(item) for item in mixed_data]
print("Mixed data tuples:")
print(result)
Mixed data tuples:
[('John', 25, 'Engineer'), ('Alice', 30, 'Designer'), ('Bob', 28, 'Developer')]
Conclusion
Use list comprehension with split() and tuple() to convert delimiter-separated strings into tuples. This approach is efficient and handles various delimiters and data types flexibly.
