一、题目
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