📌  相关文章
📜  Python - 对由分隔符分隔的单词进行排序

📅  最后修改于: 2022-05-13 01:54:34.784000             🧑  作者: Mango

Python - 对由分隔符分隔的单词进行排序

给定由一些分隔符分隔的单词字符串。任务是对字符串中给出的所有单词进行排序

Input : test_str = 'gfg:is:best:for:geeks', delim = "*" 
Output : best*for*geeks*gfg*is 
Explanation : Words sorted after separated by delim.

Input : test_str = 'gfg:is:best', delim = "*" 
Output : best*gfg*is 
Explanation : Words sorted after separated by delim. 

方法:使用 sorted() + join() + split()

以上功能的组合可以解决这个问题。在此,我们使用 split() 通过特定分隔符分隔所有单词,并转换为列表,然后执行单词排序,然后重新转换为由相同分隔符附加的字符串。

Python3
# Python3 code to demonstrate working of
# Sort words separated by Delimiter
# Using split() + join() + sorted()
 
# initializing string
test_str = 'gfg:is:best:for:geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing Delimiter
delim = ":"
 
# joining the sorted string after split
res = delim.join(sorted(test_str.split(':')))
 
# printing result
print("The sorted words : " + str(res))


输出
The original string is : gfg:is:best:for:geeks
The sorted words : best:for:geeks:gfg:is