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




On Mar 30, 2007, at 4:41 PM, Paul McGuire wrote:

On Mar 30, 2:09 pm, Michael Bentley <mich...@xxxxxxxxxxxxxxxxx> wrote:
On Mar 30, 2007, at 10:38 AM, kevinliu23 wrote:





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".

Will the first character always be a digit?

for i in yourstring.split():
if i[0].isdigit():
yourstring = yourstring.replace(i, '-%s' % (i,))

Or are these hex numbers?- Hide quoted text -

- Show quoted text -

Your replace strategy is risky. If:

yourstring = "1ab 2bc 3de 11ab"

it will convert to

-1ab -2bc -3de 1-1ab

True enough! Good catch! How's this?

for i in yourstring.split():
if i[0].isdigit():
yourstring = yourstring.replace(i, '-%s' % (i,), 1)


.



Relevant Pages

  • [TOMOYO #15 3/8] Common functions for TOMOYO Linux.
    ... This file contains common functions (e.g. policy I/O, pattern matching). ... Since TOMOYO Linux is a name based access control, ... TOMOYO Linux's string manipulation functions make reviewers feel crazy, ... the Linux kernel accepts all characters but NUL character ...
    (Linux-Kernel)
  • RfD: Escaped Strings version 4
    ... the S" string can only contain printable characters, ... the S" string cannot contain the '"' character, ... as an escape character for the entry of characters that cannot be ... \b BS (backspace, ASCII 8) ...
    (comp.lang.forth)
  • RfD: Escaped Strings version 4
    ... the S" string can only contain printable characters, ... the S" string cannot contain the '"' character, ... as an escape character for the entry of characters that cannot be ... \b BS (backspace, ASCII 8) ...
    (comp.lang.forth)
  • Re: RfD: Escaped Strings
    ... the S" string can only contain printable characters, ... the S" string cannot contain the '"' character, ... \b BS (backspace, ASCII 8) ... \ ** escapes to characters much as C does. ...
    (comp.lang.forth)
  • Re: A note on computing thugs and coding bums
    ... code is valid for any character set that is legal in C (which is a ... characters in the required source character set ... A String, in C Sharp or Java, can be redefined. ... allow programmers to handle some other data format, ...
    (comp.programming)