在Python中将集合转换为字符串
在本文中,我们将讨论如何在Python中将集合转换为字符串。它可以通过两种方式完成 -
方法 1:使用 str()
我们将在Python中使用 str()函数将 Set 转换为 String。
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
示例 1:
# create a set
s = {'a', 'b', 'c', 'd'}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
# convert Set to String
s = str(s)
print("\nAfter the conversion")
print("The datatype of s : " + str(type(s)))
print("Contents of s : " + s)
输出 :
Initially
The datatype of s :
Contents of s : {'c', 'd', 'a', 'b'}
After the conversion
The datatype of s :
Contents of s : {'c', 'd', 'a', 'b'}
示例 2:
# create a set
s = {'g', 'e', 'e', 'k', 's'}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
# convert Set to String
s = str(s)
print("\nAfter the conversion")
print("The datatype of s : " + str(type(s)))
print("Contents of s : " + s)
输出 :
Initially
The datatype of s :
Contents of s : {'k', 'g', 's', 'e'}
After the conversion
The datatype of s :
Contents of s : {'k', 'g', 's', 'e'}
方法二:使用Join()
join() 方法是一个字符串方法,它返回一个字符串,其中序列的元素已通过 str 分隔符连接起来。
句法:
string_name.join(iterable)
# create a set
s = {'a', 'b', 'c', 'd'}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
# convert Set to String
S = ', '.join(s)
print("The datatype of s : " + str(type(S)))
print("Contents of s : ", S)
输出:
Initially
The datatype of s :
Contents of s : {'c', 'd', 'a', 'b'}
The datatype of s :
Contents of s : c, d, a, b