python 字符串中各单词翻转,保留单词之间空格个数

    如下字符串:“wo shi   zhong guo ren”, 翻转后期望输出:“ren guo zhong   shi wo”,shi和zhong之间有两个空格,其余单词之间一个空格。

    用C/C++来实现的话,可以让字符串整体翻转成,"ner oug gnohz  ihs ow",然后再将每个单词翻转,结果为“ren guo zhong   shi wo”

    C/C++代码如下:

#include<iostream>
using namespace std; 

void reverse_str(char *pstr)
{
	if(NULL == pstr)
	{
		return;
	}

	char *pstart = pstr, *pcur = pstr, *pend = NULL;

	while (*pcur++ != '\0');
	pend = pcur - 2;  //减1指向字符串结束符,再减1指向字符串结尾

	while (pstart < pend)
	{
		swap(*pstart++, *pend--);
	}

        pcur = pstr;
	pstart = pstr;

	while(*pcur++ != '\0')
	{
		if((*pcur == ' ') || (*pcur == '\0'))
		{
			pend = pcur -1;
			while(pstart < pend)
			{
				swap(*pstart++, *pend--);
			}
		
			pstart = pcur + 1;	
		}
	}

	return;
}

void main()
{
	char str[] = "wo shi   zhong guo ren";
	cout << str << "\n";
	reverse_str(str);
	cout << str << "\n";

	return;
}

结果:

wo shi   zhong guo ren
ren guo zhong   shi wo
请按任意键继续. . .

用python实现的话,考虑将每个单词和空格都存在列表中,然后将列表反转,并组合成一个字符串,如下:

#!/usr/bin/python  
# -*- coding: utf-8 -*-  

import re

str = 'wo shi   zhong guo ren'
str_split = re.split('(\s+)', str)
str_split.reverse()
print "".join(str_split)
    结果: 
ren guo zhong   shi wo
split的规则加括号的话,是将匹配到的规则也保留在列表中, reverse是反转列表,然后用""和join方法将列表连接成字符串。




猜你喜欢

转载自blog.csdn.net/jishuwenming/article/details/81048039