Python中相当基本的字符串扩展? [英] Fairly Basic String Expansion in Python?

查看:114
本文介绍了Python中相当基本的字符串扩展?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试创建一个函数,它将采用'压缩'字符串,例如

I am trying to create a function that will take a 'compressed' string, for example

'a12b3c'

并返回它的'expanded'表单,对于这个例子,它将是

and return its 'expanded' form, which for this example would be

'aaaaaaaaaaaabbbc'

每个字符是应该重复多次,如下面的数字或者只是一次,如果字符后面没有数字。

Each character is supposed to be repeated as many times as the following number or just one time if no number follows the character.

我已经能够创建一个函数, 压缩字符串中的数字值只有一位数字,所以我的尝试适用于像

I have been able to create a function that will do this if the number values in the 'compressed' string are only single-digit numbers, so my attempt works for strings like

'a3b2c6'

但我似乎无法找到一种方法来考虑数字值为超过一位数字。

but I can't seem to find a way to take into account the case where the number values are more than a single digit long.

推荐答案

使用正则表达式:

>>> import re
>>> compressed = "a12b3c"
>>> expanded = ""
>>> for char, count in re.findall(r'(\w)(\d+)?', compressed):
...     count = int(count or 1)
...     expanded += char*count
... 
>>> expanded
'aaaaaaaaaaaabbbc'

这篇关于Python中相当基本的字符串扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆