Inserting '-' character in front of all numbers in a string

kyosohma at gmail.com kyosohma at gmail.com
Fri Mar 30 11:54:45 EDT 2007


On Mar 30, 10:38 am, "kevinliu23" <kevinli... at gmail.com> wrote:
> Hey guys,
>
> I want to be able to insert a '-' character in front of all numeric
> values in a string. I want to insert the '-' character to use in
> conjunction with the getopt.getopt() function.
>
> Rigt now, I'm implementing a menu system where users will be able to
> select a set of options like "2a 3ab" which corresponds to menu
> choices. However, with getopt.getopt(), it'll only return what I want
> if I input -2a -3ab as my string. I don't want the user have to insert
> a '-' character in front of all their choices, so I was thinking of
> accepting the string input first, then adding in the '-' character
> myself.
>
> So my qusetion is, how do I change:
>
> "2a 3ab" into "-2a -3ab".
>
> Regular expressions? :/

Regular expressions would definitely work. Here's a hack though:

tempInput = '2a 3ab'
tempLst = tempInput.split(' ')

output = ''
for i in tempLst:
   output += ('-' + i + ' ')


I'm sure there are many better and more elegant hacks than this.

Mike




More information about the Python-list mailing list