473,796 Members | 2,426 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to use python regular expression to substitute string value

Hi,
I am new to python. I would like to know how to use python regular
expression to substitute string value?
I have an input string like this:
x:11 y:0 w:760 h:19 area:14440 areaPerCent:0
totalAreaPerCen t:-3.08011e+16 type:3 path:///-/1/1

and I would like to convert it to:
rect x="11" y="0" width="760" height="14440"

all I care about the input string is x, y, w, h.

Thank you for any pointers.

Feb 26 '06 #1
7 3178
Al************@ gmail.com writes:
Hi,
I am new to python. I would like to know how to use python regular
expression to substitute string value?
I have an input string like this:
x:11 y:0 w:760 h:19 area:14440 areaPerCent:0
totalAreaPerCen t:-3.08011e+16 type:3 path:///-/1/1

and I would like to convert it to:
rect x="11" y="0" width="760" height="14440"

all I care about the input string is x, y, w, h.


I'd say you're better off with 'findall':
- -
import re
line = "x:11 y:0 w:760 h:19 area:14440 areaPerCent:0 totalAreaPerCen t:-3.08011e+16 type:3 path:///-/1/1"
pattern = "x:(\d+) y:(\d+) w:(\d+) h:(\d+) area:(\d+)"
x, y, width, height, area = re.findall(patt ern, line)[0]
print "rect x=\"%(x)s\" y=\"%(y)s\" width=\"%(width )s\" height=\"%(heig ht)s\" ..." % locals()
- -

x .. area are strings when they come out of findall, so you may want to:
- -
x .. area = map (lambda x: int(x), re.findall (pattern, line)[0]
- -

--
Psi -- <http://www.iki.fi/pasi.savolainen >
Feb 26 '06 #2
Thanks. But i don't understand why I need to do this:
x. . area = map (lambda x: int(x), re.findall (pattern, line)[0]

if i have the value already by doing this:
x, y, width, height, area = re.findall(patt ern, line)[0]
print "rect x=\"%(x)s\" y=\"%(y)s\" width=\"%(width )s\"
height=\"%(heig ht)s\" ..." % locals()

Feb 26 '06 #3
You don't really need regexes for this.

Assuming there is no whitespace in any of your values, it should be
really easy to parse the string.

s = 'x:11 y:0 w:760 h:19 area:14440 areaPerCent:0
totalAreaPerCen t:-3.08011e+16 type:3 path:///-/1/1'

s.split() # break the string on whitespace
['x:11', 'y:0', 'w:760', 'h:19', 'area:14440', 'areaPerCent:0' , 'totalAreaPerCe nt:-3.08011e+16', 'type:3', 'path:///-/1/1']
[ t.split(':',1) for t in s.split() ] # break each term on the first
':' [['x', '11'], ['y', '0'], ['w', '760'], ['h', '19'], ['area', '14440'], ['areaPerCent', '0'], ['totalAreaPerCe nt', '-3.08011e+16'], ['type', '3'], ['path', '///-/1/1']]
d = dict([ t.split(':',1) for t in s.split() ]) # make a dict of the
list {'type': '3', 'area': '14440', 'h': '19', 'w': '760', 'areaPerCent': '0', 'y': '0', 'x': '11', 'path': '///-/1/1', 'totalAreaPerCe nt': '-3.08011e+16'}
Now you can do this:
new_s = 'rect x="%(x)s" y="%(y)s" width="%(w)s" height="%(h)s"' % d 'rect x="11" y="0" width="760" height="19"'


Feb 26 '06 #4
okay, but I have a simpler question, how can I split using only "\n"?

I try this:
strings = node.data.split ("\n");
print node.data

for str in strings:
print str

where node.data has multiple lines, but in the for loop, I don't see
str gets print out.

Feb 26 '06 #5
Are you sure node.data contains newlines?
You could try just:
print node.data
print node.data.split ('\n')

This should give you an idea. From the interpreter:
s = """ .... abc
.... def
.... xyz""" s.split('\n')

['', 'abc', 'def', 'xyz']

Feb 26 '06 #6
When I try your idea, I have this error

x, y, width, height = re.findall(patt ern, str)[0]
IndexError: list index out of range

How can I use findall to handle error case? i.e. what if there is no
match? how can I handle it gracefully?

Feb 26 '06 #7
Al************@ gmail.com writes:
When I try your idea, I have this error

x, y, width, height = re.findall(patt ern, str)[0]
IndexError: list index out of range

How can I use findall to handle error case? i.e. what if there is no
match? how can I handle it gracefully?


This is explained in python docs, and do try them in interactive python,
for example IPython is great for this stuff.

- -
ipython ->

In [1]:import re

In [2]:line = "foobar"

In [3]:re.findall ("baz", line)
Out[3]:[]

In [4]:re.findall ("o", line)
Out[4]:['o', 'o']
- -

So you can do:
- -
match = re.findall(patt ern, str)
if match:
x, y, width, height = match[0]
...
else:
# no match
- -

--
Psi -- <http://www.iki.fi/pasi.savolainen >
Feb 26 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
8295
by: Chris Lasher | last post by:
Hello, I would like to create a set of very similar regular expression. In my initial thought, I'd hoped to create a regular expression with a variable inside of it that I could simply pass a string into by defining this variable elsewhere in my module/function/class where I compile the regular expression, thus making for an easy substitution. However, still after JFGI'ing, I still cannot find the syntax to place a variable inside a...
25
497
by: Byte | last post by:
I know this is probably a stupid question, but I'm learning Python, and am trying to get the if function to work with letters/words. Basicly, I'm trying to write a script that when run, says Please enter your name: Then, if the user types myself as the name , the output is OK. Thats all I want it to do (remember, Im just new). The code Ive tryed is:
25
5171
by: Mike | last post by:
I have a regular expression (^(.+)(?=\s*).*\1 ) that results in matches. I would like to get what the actual regular expression is. In other words, when I apply ^(.+)(?=\s*).*\1 to " HEART (CONDUCTION DEFECT) 37.33/2 HEART (CONDUCTION DEFECT) WITH CATHETER 37.34/2 " the expression is "HEART (CONDUCTION DEFECT)". How do I gain access to the expression (not the matches) at runtime? Thanks, Mike
5
2230
by: antar2 | last post by:
Hello, I am a beginner in Python and am not able to use a list element for regular expression, substitutions. list1 = list2 = Suppose that I want to substitute the vowels from list2 that are in list1, into for example 'u'.
0
9680
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10230
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10174
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10012
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7548
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5575
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4118
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2926
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.