【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 here
    return "-".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

 

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值