欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > 【Python】字符串操作:split() 与 join()

【Python】字符串操作:split() 与 join()

2024/10/24 9:22:44 来源:https://blog.csdn.net/u010528690/article/details/140629239  浏览:    关键词:【Python】字符串操作:split() 与 join()

一、题目

In Python, a string can be split on a delimiter.

Example:

>>> a = "this is a string"

>>> a = a.split(" ") # a is converted to a list of strings.

>>> print a 

['this', 'is', 'a', 'string']

Joining a string is simple:

>>> a = "-".join(a)

>>> print a

this-is-a-string

 Task:

You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen.

Sample Input

this is a string

Sample Outpu

this-is-a-string

 

二、代码

def split_and_join(line):# write your code herereturn "-".join(line.split())if __name__ == '__main__':line = input()result = split_and_join(line)print(result)

三、解读

在Python中,split() 和 join() 是两种非常常用的字符串操作方法,它们在处理字符串时非常有用。

以下是两种方法的详细介绍和用法:

split()

  • 目的:将字符串分割成一个列表,根据指定的分隔符划分。
  • 语法:string.split(<separator>, <maxsplit>)
    • <separator>:用于分割字符串的字符或字符串。如果不提供,则以空格作为分割符。
    • <maxsplit>:可选参数,指定分割的最大次数,默认为-1(无限制)。
text = "hello world, welcome to the world of Python"# 默认以空格分割
words = text.split()
print(words) # 输出:['hello', 'world', 'welcome', 'to', 'the', 'world', 'of', 'Python']# 指定分割符为逗号
words = text.split(',')
print(words) # 输出:['hello world' , ' welcome to the world of Python']

join()

  • 目的:将序列中的元素连接成一个字符串,元素之间用指定的字符串连接。
  • 语法:string.join(<iterable>)
    • <iterable>:一个迭代器,其元素将会被连接成字符串。
# 创建一个字符串列表
words = ['hello', 'world', 'Python']# 使用空格连接字符串
sentence = ' '.join(words)
print(sentence) # 输出: hello world Python# 使用特定字符连接字符串
sentence = '---'.join(words)
print(sentence) # 输出: hello----world----Python

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com