Convert a tuple to a string in Python
This post will discuss how to convert a tuple to a string Python.
1. Using join() function
The idea is to use the built-in function str.join, which returns the concatenation of the strings in an iterable.
|
1 2 3 4 5 6 |
if __name__ == '__main__': tup = ('A', 'B', 'C') s = ''.join(tup) print(s) # ABC |
If you need a comma-separated string or a string separated with some other delimiter, you can use the following code:
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': tup = ('A', 'B', 'C') delim = ',' s = delim.join(tup) print(s) # A,B,C |
This will raise a TypeError for any non-string values in the tuple. For example, it fails when the tuple contains numbers. To handle this, you can use the map function:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': tup = (1, 2, 3) s = ''.join(map(str, tup)) print(s) # 123 |
2. Using reduce operation
Another option is to perform a reduction operation using the functools.reduce function.
|
1 2 3 4 5 6 7 8 9 |
from functools import reduce if __name__ == '__main__': tup = ('A', 'B', 'C') s = reduce(lambda x, y: x + y, tup, '') print(s) # ABC |
This will raise a TypeError for any non-string values in the tuple. To handle this, you can use the string constructor:
|
1 2 3 4 5 6 7 8 9 |
from functools import reduce if __name__ == '__main__': tup = (1, 2, 3) s = reduce(lambda x, y: str(x) + str(y), tup, '') print(s) # 123 |
That’s all about converting a tuple to a string Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)