Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Converting from Tuple to String?

let's say that I have string:

    s = "Tuple: "

and Tuple (stored in a variable named tup):

    (2, a, 5)

I'm trying to get my string to contain the value "Tuple: (2, a, 5)". I noticed that you can't just concatenate them. Does anyone know the most straightforward way to do this? Thanks.

like image 976
Jacob Griffin Avatar asked Mar 01 '12 22:03

Jacob Griffin


People also ask

How do you print a tuple as a string?

Use a formatted string literal to print a tuple with string formatting, e.g. print(f'Example tuple: {my_tuple}') . Formatted string literals let us include expressions and variables inside of a string by prefixing the string with f .

How do you convert a tuple to a variable in Python?

Summary. Python uses the commas ( , ) to define a tuple, not parentheses. Unpacking tuples means assigning individual elements of a tuple to multiple variables. Use the * operator to assign remaining elements of an unpacking assignment into a list and assign it to a variable.

How do you convert a tuple to an integer in Python?

Method 3: str() + map() + join() You can pass the str() function into the map() function to convert each tuple element to a string. Then, you can join all strings together to a big string. After converting the big string to an integer, you've successfully merged all tuple integers to a big integer value.

Can tuple be converted to list in Python?

Python list method list() takes sequence types and converts them to lists. This is used to convert a given tuple into list. Note − Tuple are very similar to lists with only difference that element values of a tuple can not be changed and tuple elements are put between parentheses instead of square bracket.


1 Answers

This also works:

>>> s = "Tuple: " + str(tup)
>>> s
"Tuple: (2, 'a', 5)"
like image 170
Bi Rico Avatar answered Oct 24 '22 07:10

Bi Rico