Python字符串逐字符或逐词反转方法

WBOY
Release: 2016-06-10 15:12:01
Original
1326 people have browsed it

目的

  把字符串逐字符或逐词反转过来,这个蛮有意思的。

方法

  先看逐字符反转吧,第一种设置切片的步长为-1

复制代码 代码如下:

  revchars=astring[::-1]

In [65]: x='abcd'

In [66]: x[::-1]
Out[66]: 'dcba'

第二种做法是采用reversed(),注意它返回的是一个迭代器,可以用于循环或传递给其它的“累加器”,不是一个已完成的字符串。

复制代码 代码如下:

revchars=''.join(reversed(astring))

In [56]: y=reversed(x)

In [57]: y
Out[57]:

In [58]: ''.join(y)
Out[58]: 'dcba'


接着来看逐词反转。

第一种做法,创建一个列表,将列表反转,用join方法合并

复制代码 代码如下:

In [38]: s='Today is really a good day'

In [39]: rev=s.split()

In [40]: rev
Out[40]: ['Today', 'is', 'really', 'a', 'good', 'day']

In [41]: rev.reverse()

In [42]: rev
Out[42]: ['day', 'good', 'a', 'really', 'is', 'Today']

In [45]: ' '.join(rev)
Out[45]: 'day good a really is Today'

也有一行解决的代码:

复制代码 代码如下:

rev=' '.join(s.split()[::-1])

第二种做法,可以不改变原先的空格,采用正则式来做:

复制代码 代码如下:

In [46]: import re

In [47]: rev=re.split(r'(\s+)',s)

In [48]: rev
Out[48]: ['Today', ' ', 'is', ' ', 'really', ' ', 'a', ' ', 'good', ' ', 'day']

In [49]: rev.reverse()

In [50]: rev
Out[50]: ['day', ' ', 'good', ' ', 'a', ' ', 'really', ' ', 'is', ' ', 'Today']

In [51]: rev=''.join(rev)

In [52]: rev
Out[52]: 'day good a really is Today'


可以考虑采用reversed()来代替可读性较差的[::-1]

复制代码 代码如下:

revwords=' '.join(reversed(s.split()))

revwords=''.join(reversed(re.split(r'(\s+)',s)))

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!