python3 split()、list()、join()

split()
list()
join()

1. split()
将句子分成单词

>>> A = 'Mary had a little rabbit'
>>> A.split() 
['Mary', 'had', 'a', 'little', 'rabbit'] 

空白字符包括空格’ ‘,换行符’\ n’和制表符’\ t’等。.split()分隔这些字符的任何组合序列:

>>> B = 'color    green \n\tidea\n'      
>>> print(B)
 color   green 
	idea
 
>>> B.split()
>['color', 'green', 'idea'] 

.split(‘x’)可用于在特定子字符串’x’上拆分字符串。如果没有指定’x’,split ()只是在所有空白符上分割,如上所示。

>>> C = 'Mary had a little lamb'
>>> C.split('a')               
['M', 'ry h', 'd ', ' little l', 'mb'] 
>>> D= 'Hello mother,\nHello father.'
>>> print(D)
Hello mother,
Hello father. 
>>> D.split()               
['Hello', 'mother,', 'Hello', 'father.'] 
>>> D.split('\n')              
['Hello mother,', 'Hello father.'] 

2. list()
将一个字符串拆分成一个字符列表。在Python中,字符只是长度为1的字符串。list()函数将字符串转换为单个字母的列表。

>>> list('hello world')
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

有一个单词列表,你如何将它们重新组合成一个字符串?此时要用.join()。
3. join()
‘x’.join(y)连接列表y中由’x’分隔的每个元素。

>>> mwords
['Mary', 'had', 'a', 'little', 'lamb'] 
>>> ' '.join(mwords)
'Mary had a little lamb'

可以对任何分隔符字符串进行连接。下面,使用’ – ‘和制表符’\ t’。

>>> '--'.join(mwords)
'Mary--had--a--little--lamb' 
>>> '\t'.join(mwords)
'Mary\thad\ta\tlittle\tlamb' 
>>> print('\t'.join(mwords))
Mary    had     a       little  lamb 

下面,将一个字符列表放回到原始字符串中:

>>> hi = 'hello world'
>>> hichars = list(hi)
>>> hichars
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] 
>>> ''.join(hichars)
'hello world' 

题目:将一个英文语句以单词为单位逆序排放。例如“I am a boy”,逆序排放后为“boy a am I”
所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符。(来自牛客https://www.nowcoder.com/questionTerminal/48b3cb4e3c694d9da5526e6255bb73c3)

#python3
print(" ".join(input().split()[::-1]))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值