Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > RE: quick regex question

Reply
Thread Tools

RE: quick regex question

 
 
Robert Brewer
Guest
Posts: n/a
 
      10-28-2004
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
http://www.velocityreviews.com/forums/(E-Mail Removed)
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
How make regex that means "contains regex#1 but NOT regex#2" ?? seberino@spawar.navy.mil Python 3 07-01-2008 03:06 PM
Quick question, hopefully quick answer. ~misfit~ NZ Computing 114 01-06-2005 01:36 PM
quick regex question Matt Price Python 0 10-28-2004 04:46 PM
Quick Question Quick Answer JKop C++ 11 05-24-2004 09:46 PM



Advertisments