How to convert python tuple to string

1 year ago Lalit Bhagtani 0

In this tutorial, we will learn about converting python tuple to string object.

Python Tuple To String

For converting Tuple object to String, we will use String’s join method.

Syntax : < String Object >.join(< Iterable Object >)

This method returns a string, which is a concatenation of all the strings in a tuple ( iterable ). The separator between the elements of the tuple is a string object on which join method is called. An Exception ( Type Error ) will be raised, if tuple contains any non-string element.

Example:

[datacamp_exercise lang=”python” height=”400″ min-height=”300″ max-height=”500″]
[datacamp_pre_exercise_code]

[/datacamp_pre_exercise_code]
[datacamp_sample_code]
# create tuple object and assign it to variable t
t = (‘Jan’,’Feb’,’Mar’,’Jan’)

# create single space string and assign it to variable separator
separator = ‘ ‘

# call join() method on separator by passing tuple t as an argument
output = separator.join(t)

# print the value of variable output
print(output)

# second example with ‘-‘ as a separator
separator = ‘-‘

output = separator.join(t)

print(output)
[/datacamp_sample_code]
[datacamp_solution]

[/datacamp_solution]
[/datacamp_exercise]

References :-

  1. String Join Method Docs

You can also check :- 

  1. Python Tuple
  2. Python String

That’s all for How to convert python tuple to string, you can learn more about tuple . If you liked it, please share your thoughts in comments section and share it with others too.