RE: quick regex question

Discussion in 'Python' started by Robert Brewer, Oct 28, 2004.

  1. Matt Price wrote:
    > this is surely trivial, but can'f figure it out. I wnat to replace:
    >
    > 'string with spaces'
    > with
    > 'StringWithSpaces'
    >
    > so I tried this:
    >
    > s = 'string with spaces'
    > pat = ' (.)'
    > t = re.sub(pat, upper, s)
    >
    > I know this isn't quite right, I expect it to return:
    > 'String With Spaces'


    A couple things are tricky about what you want.

    1. If you use a function for the replacement arg in re.sub, it receives
    a Match object, not the string, so you need to write a function to pull
    the matching text out of the Match object:

    def up_it(m):
    return m.group(1).upper()

    2. Your pattern doesn't address the start of the string. You probably
    want "non-grouping" parentheses to handle the "or".

    >>> re.sub(r'(?:^| )(.)', up_it, 'string with spaces')

    'StringWithSpaces'


    Robert Brewer
    MIS
    Amor Ministries
     
    Robert Brewer, Oct 28, 2004
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. JKop
    Replies:
    11
    Views:
    923
  2. Matt Price

    quick regex question

    Matt Price, Oct 28, 2004, in forum: Python
    Replies:
    0
    Views:
    649
    Matt Price
    Oct 28, 2004
  3. Steven Bethard

    Re: quick regex question

    Steven Bethard, Oct 28, 2004, in forum: Python
    Replies:
    5
    Views:
    625
    Peter Otten
    Oct 29, 2004
  4. Replies:
    3
    Views:
    810
    Reedick, Andrew
    Jul 1, 2008
  5. Jürgen Exner

    Re: Quick perl script-regex question

    Jürgen Exner, Nov 4, 2011, in forum: Perl
    Replies:
    0
    Views:
    2,009
    Jürgen Exner
    Nov 4, 2011
Loading...

Share This Page