In this article, we will discuss how to convert a set to a string in Python. It can done using two ways –
Method 1: Using str() We will convert a Set into a String in Python using the str() function.
Syntax : str(object, encoding = ’utf-8?, errors = ’strict’)
Parameters :
- object : The object whose string representation is to be returned.
- encoding : Encoding of the given object.
- errors : Response when decoding fails.
Returns : String version of the given object
Example 1 :
python3
s = {'a', 'b', 'c', 'd'}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
s = str(s)
print("\nAfter the conversion")
print("The datatype of s : " + str(type(s)))
print("Contents of s : " + s)
|
Output :
Initially
The datatype of s : <class 'set'>
Contents of s : {'c', 'd', 'a', 'b'}
After the conversion
The datatype of s : <class 'str'>
Contents of s : {'c', 'd', 'a', 'b'}
Example 2 :
python3
s = {'g', 'e', 'e', 'k', 's'}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
s = str(s)
print("\nAfter the conversion")
print("The datatype of s : " + str(type(s)))
print("Contents of s : " + s)
|
Output :
Initially
The datatype of s : <class 'set'>
Contents of s : {'k', 'g', 's', 'e'}
After the conversion
The datatype of s : <class 'str'>
Contents of s : {'k', 'g', 's', 'e'}
Method 2: Using Join() The join() method is a string method and returns a string in which the elements of sequence have been joined by str separator.
Syntax:
string_name.join(iterable)
python3
s = {'a', 'b', 'c', 'd'}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
S = ', '.join(s)
print("The datatype of s : " + str(type(S)))
print("Contents of s : ", S)
|
Output:
Initially
The datatype of s : <class 'set'>
Contents of s : {'c', 'd', 'a', 'b'}
The datatype of s : <class 'str'>
Contents of s : c, d, a, b
Method 2: Using functools.reduce()
Syntax:
functools.reduce(function, set)
Approach:
- Initialize the set.
- Use reduce function which takes a function and sets it as parameters.
- The function applies to each item of the set.
- Function concatenate the items of the set.
Python
from functools import reduce
s = {'a', 'b', 'c', 'd'}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
S = reduce(lambda a, b : a+', '+b , s)
print("The datatype of s : " + str(type(S)))
print("Contents of s : ", S)
|
Output:
Initially
The datatype of s : <class 'set'>
Contents of s : {'a', 'c', 'd', 'b'}
The datatype of s : <class 'str'>
Contents of s : a, c, d, b
Time complexity: O(N) N is the length of the set over which reduce function iterate.
Space complexity: O(1) Because no extra space is used.
Last Updated :
05 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...