Python程序来拆分和连接字符串

Python程序,根据分隔符拆分字符串,并使用另一个分隔符连接字符串。

null

拆分字符串有时非常有用,尤其是当您只需要字符串的某些部分时。一个简单而有效的例子是将一个人的名字和姓氏分开。另一个应用程序是CSV(逗号分隔文件)。我们使用split从CSV获取数据,并使用join将数据写入CSV。

在Python中,我们可以使用函数 split() 拆线 加入 连接一根绳子。有关split()和join()函数的详细文章,请参阅以下内容: Python中的split() Python中的join() .

例如:

Split the string into list of strings

Input : Geeks for Geeks
Output : ['Geeks', 'for', 'Geeks']


Join the list of strings into a string based on delimiter ('-')

Input :  ['Geeks', 'for', 'Geeks']
Output : Geeks-for-Geeks

下面是基于分隔符拆分和连接字符串的Python代码:

# Python program to split a string and
# join it using different delimiter
def split_string(string):
# Split the string based on space delimiter
list_string = string.split( ' ' )
return list_string
def join_string(list_string):
# Join the string based on '-' delimiter
string = '-' .join(list_string)
return string
# Driver Function
if __name__ = = '__main__' :
string = 'Geeks for Geeks'
# Splitting a string
list_string = split_string(string)
print (list_string)
# Join list of strings into one
new_string = join_string(list_string)
print (new_string)


输出:

['Geeks', 'for', 'Geeks']
Geeks-for-Geeks
© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享