Python 3: Converting A Tuple To A String
Solution 1
Your code looks fine as is.
Try running import pdb; pdb.set_trace()
in your program to see if you can find the line triggering the error.
EDIT: You'll want to use ''.join(var_four)
to convert var_four
into a string before adding it to whatever it is you want to use it. Please note that this will actually create a new string and not overwrite var_four
. See Python 3 string.join() equivalent?
Also, you should be using the subprocess
module instead of os.system
. See the Python 3.x documentation.
Solution 2
one_big_string = ''.join(tuple)
print one_big_string
Solution 3
What you've written is fine:
>>> x = 1
>>> y = 1, x
>>>
The problem is that somewhere else in your code, you're using var_four
as a string where it should be a tuple.
BTW, I think it's neater to put parentheses around tuples like this; otherwise I tend to think they're being used in tuple unpacking.
EDIT: There are all sorts of ways to join and format strings -- Python is good at that. In somewhat-decreasing order of generality:
"{first_thing} {second_thing}".format(first_thing=var_one, second_thing=var_two)
"{0} {1}".format(var_one, var_two)
var_one + var_two
Eden Crow
Updated on March 09, 2020Comments
-
Eden Crow about 4 years
I have the following code:
var_one = var_two[var_three-1] var_one = "string_one" + var_1
And I need to do the following to it:
var_four = 'string_two', var_one
However, this returns the following error:
TypeError: Can't convert 'tuple' object to str implicity
I have tried things such as
str(var_one)
and usingstrip
but these did not work. What can I do to achieve the result I require?EDIT - Here are what the variables contain:
var_one: new variable
var_two: tuple
var_three: integer
var_four: new
EDIT2:
The line in the program that makes the error is:
os.system(var_four)