Turn a List to a String and Back Python

In this tutorial you will see how to convert a tuple to a string in Python. We will go through few examples you will find useful for your own applications.

The simplest method to convert a tuple to a string in Python is with the str.join() method that generates a string by concatenating the strings in a tuple. This works fine if the elements of the tuple are strings, otherwise an alternative approach is required, for example by using the map function.

We will start with a simple example and then go through different scenarios you might also encounter in your Python programs.

Let's start coding!

Converting a Python Tuple to String and Back

Let's say I have the following tuple of strings:

          >>> codefather = ('c','o','d','e','f','a','t','h','e','r')                  

If it's the first time you see a tuple you might wonder how you could print it without brackets but just as a single string.

To convert this tuple into a single string we can use the string join method that concatenates the strings in a iterable and creates a single string.

In this case our iterable is a tuple but it could also be a list or a set.

          >>> ''.join(codefather) 'codefather'                  

As you can see we have applied the join method to an empty string that acts as delimiter between each character in the final string.

To convert this string back to a tuple we have to split our string into a tuple of characters. To do that we can use the tuple() function.

          >>> codefather = 'codefather' >>> tuple(codefather) ('c', 'o', 'd', 'e', 'f', 'a', 't', 'h', 'e', 'r')                  

Makes sense?

Convert Python Tuple to a String with a Comma Delimiter

There might be scenarios in which you would like to use the comma as separator when converting a tuple into a string.

For example, let's take a tuple that contains the names of planets:

          >>> planets = ('earth','mars','saturn','jupiter')                  

If we use the join method in the same way we have done in the previous section we get the following:

          >>> ''.join(planets) 'earthmarssaturnjupiter'                  

To make it readable we want to have a comma between each string in the tuple.

We can pass a different delimiter as string to which we apply the join method (in the previous example our delimiter was an empty string).

          >>> ','.join(planets) 'earth,mars,saturn,jupiter'                  

For a cleaner code we can also store the delimiter in a variable, this can be handy in case we want to change the delimiter later on.

          >>> delimiter = ',' >>> delimiter.join(planets) 'earth,mars,saturn,jupiter'                  

Convert a Tuple that Contains Numbers to a String

Let's see what happens if we apply the join method to a tuple that contains a mix of strings and integers:

          >>> values = ('radius', 34) >>> ''.join(values) Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: sequence item 1: expected str instance, int found                  

The error "sequence item 1: expected str instance, int found" tells us that the element of the tuple identified by index 1 should be a string but it's an int instead.

This error is also clarified by the official Python documentation for the join method:

Python join method

So, to make this work we have to convert any numbers in the tuple into strings first. And to do that we can use a list comprehension.

          >>> values = ('radius', 34) >>> delimiter = ',' >>> delimiter.join([str(value) for value in values]) 'radius,34'                  

The list comprehension converts our tuple into a list where every item is a string. Then the list is passed to the join method.

To clarify how this works, if you are not familiar with list comprehensions, you can see the output below that shows what the list comprehension generates:

          >>> [str(value) for value in values] ['radius', '34']                  

The same applies if our tuple contains floats:

          >>> values = (3.14, 5.67, 7.89) >>> ''.join(values) Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: sequence item 0: expected str instance, float found                  

We get an exception when trying to use the join method directly. And as alternative we can use the same list comprehension used before:

          >>> delimiter = ',' >>> delimiter.join([str(value) for value in values]) '3.14,5.67,7.89'                  

Using Map to Convert a Tuple of Numbers into a String

Let's see how we can use the map function to convert a tuple of numbers into a string instead of using a list comprehension (see section above).

Firstly, here is what the map function does…

If we pass the str function as first argument and our tuple as second argument we get the following:

          >>> values = (3.14, 5.67, 7.89) >>> map(str, values) <map object at 0x101125970>                  

We can actually pass this map object to the tuple function to see the difference between this object and the initial tuple:

          >>> tuple(map(str, values)) ('3.14', '5.67', '7.89')                  

Notice how this time every element of the tuple is a string and not a float.

Now, let's use map together with join to create a string from our tuple of numbers.

          >>> ' '.join(map(str, values)) '3.14 5.67 7.89'                  

Et voilà! 🙂

How to Convert a Tuple of Bytes to a String

The bytes() function can be used to return a bytes object. It can also be used to convert objects (e.g. a tuple) into bytes objects.

Here are some ways to use the bytes() function…

Generate a bytes object with length 5 filled with zeros

          >>> bytes(5) b'\x00\x00\x00\x00\x00'        

Generate a bytes object using the range function

          >>> bytes(range(10)) b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t'                  

But here we want to see how to convert a tuple of bytes to a string.

Here's how we can generate the same bytes object we have created using the range function but this time by starting from a tuple:

          >>> bytes(tuple([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])) b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t'                  

Convert a Tuple that Represents a Date into a String

Let's work on a different use case for a tuple…

I have a tuple with three elements where the first element represents the day of the month, the second the month and the third the year.

          >>> date_tuple = (3, 7, 2021)        

How can I convert it into a string that shows the full date?

Let's look at the official documentation for the datetime module.

Can we use the datetime.date method?

Here is what it does according to its help manual:

          class date(builtins.object)  |  date(year, month, day) --> date object  |        

Let's try to pass the first item of our tuple to it and see what happens:

          >>> datetime.date(date_tuple[0]) Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: function missing required argument 'month' (pos 2)                  

Ok, it's expecting the month in position 2…

          >>> datetime.date(date_tuple[0], date_tuple[1]) Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: function missing required argument 'day' (pos 3)                  

And now it's expecting the day in position 3…

Hmmm, this is not what I wanted considering that in our tuple the day is the first element.

Let's see if we can use keyword arguments with datetime.date.

          >>> datetime.date(day=date_tuple[0], month=date_tuple[1], year=date_tuple[2]) datetime.date(2021, 7, 3)                  

It's working, let's store this into a variable and then let's print the string associated to this object. We will use the datetime.ctime() function to print the string version of it.

          >>> date_object.ctime() 'Sat Jul  3 00:00:00 2021'                  

That's enough for this example. Feel free to explore more functions in the datetime module.

Convert a List of Numeric Tuples to a List of String Tuples

Let's look at something a bit more complex.

Starting from the following list of tuples:

          data = [(1,2,3),(4,5,6)]        

I want to generate a list of tuples where every item in a tuple is a string instead of a number.

Basically we want the following result:

          [('1','2','3'),('4','5','6')]        

First approach

We use a for loop that reads each tuple in the list and converts it into a tuple of strings using the map function.

Each tuple is then added to the new_data list using the list append method:

          data = [(1,2,3),(4,5,6)] new_data = []  for item in data:     new_data.append(tuple(map(str, item)))  print(new_data)  [output] [('1', '2', '3'), ('4', '5', '6')]        

Second approach

Here is how the previous example becomes if we use a list comprehension.

We start with the following code from the previous example:

          tuple(map(str, item))        

Let's take a single tuple and see what it returns:

          >>> item = (1,2,3) >>> tuple(map(str, item)) ('1', '2', '3')                  

Now we can use this expression as part of a list comprehension:

          >>> [tuple(map(str, item)) for item in data] [('1', '2', '3'), ('4', '5', '6')]                  

Third approach

We can also write a one-liner that uses two for loops.

          >>> [tuple([str(x) for x in item]) for item in data] [('1', '2', '3'), ('4', '5', '6')]                  

I'm not a huge fun of this one because the code is becoming harder to read. I find the second approach better.

Conclusion

We went through quite a lot of different ways to convert a Python tuple to a string.

Now you know how you can use the join method, the map function and list comprehensions to create the best implementation you want.

And you, which approach do you prefer amongst the ones we have seen?

Share knowledge with your friends!

    Turn a List to a String and Back Python

    Source: https://codefather.tech/blog/tuple-to-string-python/

    0 Response to "Turn a List to a String and Back Python"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel