[Tutor] Changing only intergers in a list of strings

Juan Manuel Lopez Baio jmbaio at gmail.com
Wed Feb 5 16:47:38 CET 2014


On Wed, Feb 5, 2014 at 7:47 AM, David Palao <dpalao.python at gmail.com> wrote:
> Sorry, there is a typo:
> "(num+a,)" should be "(num+1,)", obviously.
>
> 2014-02-05 David Palao <dpalao.python at gmail.com>:
>> Hi,
>> Is it not clear to me if you must distinguish ints from other type of
>> numbers, or if, for instances floats and ints must be dealt
>> differently.
>> Anyway, I would propose something like the following function:
>>
>> def FindNumbers(a_string):
>>     print "You entered:", a_string
>>     out_list = []
>>     for item in a_string.split():
>>         try:
>>             num = int(item)
>>         except ValueError:
>>             out_list.append(item)
>>         else:
>>             out_list.append("%s" % (num+a,))
>>         out_string = ' '.join(out_list)
>>         # do whatever you want to do with the resulting out_string:
>> return it, or display it...

hi, I thought it might be interesting to make this work for cases
where the numbers are not necessarily "word-separated"
i.e., something like '12this is a rather odd string,3 I know 32. '

with regular expressions, I managed this:

>>> import re
>>> st = '12this is a rather odd string,3 I know 32. '
>>> pattern = r'(\d+|\D+)'   # any digit one or more times OR any non-digit one or more times
>>> re.findall(pattern,st)
['12', 'this is a rather odd string,', '3', ' I know ', '32', '. ']

which allows me to increment each integer and reconstruct the string,
just iterating through the list.

now, I would like to construct a pattern such that this next
alternative usage works (my intention is to embed the 'findall' logic
in the pattern itself):
>>>re.search(pattern,st).groups()

returning a tuple instead of a list, but with the same elements as
before. I've been trying for a while and can't find a way to make it
work. Does anyone know if this is possible?

thank you


More information about the Tutor mailing list