hi
say i have string like this
astring = 'abcd efgd 1234 fsdf gfds abcde 1234'
if i want to find which postion is 1234, how can i achieve this...? i
want to use index() but it only give me the first occurence. I want to
know the positions of both "1234"
thanks 14 22538
> say i have string like this astring = 'abcd efgd 1234 fsdf gfds abcde 1234' if i want to find which postion is 1234, how can i achieve this...? i want to use index() but it only give me the first occurence. I want to know the positions of both "1234"
Well, I'm not sure how efficient it is, but the following
seemed to do it for me: a = 'abcd efgd 1234 fsdf gfds abcde 1234' thing = '1234' offsets = [i for i in range(len(a)) if
a.startswith(th ing, i)] print offsets
[10, 31]
HTH,
-tkc mi*******@hotma il.com wrote: hi say i have string like this astring = 'abcd efgd 1234 fsdf gfds abcde 1234' if i want to find which postion is 1234, how can i achieve this...? i want to use index() but it only give me the first occurence. I want to know the positions of both "1234" thanks
==========
def getAllIndex(aSt ring=None, aSub=None):
t=dict()
c=0
ndx=0
while True:
try:
ndx=aString.ind ex(aSub, ndx)
t[c]=ndx
ndx += 1
c += 1
except ValueError:
break
return t
===========
This will return a dictionary of what was found; i.e., getAllIndex('ab cd 1234 efgh 1234 ijkl', '1234')
{0: 5, 1: 15}
alisonken1 wrote: ========== def getAllIndex(aSt ring=None, aSub=None): t=dict() c=0 ndx=0 while True: try: ndx=aString.ind ex(aSub, ndx) t[c]=ndx ndx += 1 c += 1 except ValueError: break return t ===========
This will return a dictionary of what was found; i.e.,
getAllIndex('ab cd 1234 efgh 1234 ijkl', '1234')
{0: 5, 1: 15}
Consecutive integers starting at 0 as keys? Looks like you want a list
instead of a dict.
Peter mi*******@hotma il.com wrote: astring = 'abcd efgd 1234 fsdf gfds abcde 1234' <paraphrase> i want to find all positions of '1234' in astring.</paraphrase>
def positions(targe t, source):
'''Produce all positions of target in source'''
pos = -1
try:
while True:
pos = source.index(ta rget, pos + 1)
yield pos
except ValueError:
pass
print list(positions( '1234', 'abcd efgd 1234 fsdf gfds abcde 1234'))
prints:
[10, 31]
--Scott David Daniels sc***********@a cm.org mi*******@hotma il.com writes: say i have string like this astring = 'abcd efgd 1234 fsdf gfds abcde 1234' if i want to find which postion is 1234, how can i achieve this...? i want to use index() but it only give me the first occurence. I want to know the positions of both "1234"
Most straightforward ly with re.findall -- see the docs. mi*******@hotma il.com wrote: hi say i have string like this astring = 'abcd efgd 1234 fsdf gfds abcde 1234' if i want to find which postion is 1234, how can i achieve this...? i want to use index() but it only give me the first occurence. I want to know the positions of both "1234" thanks
The regular expression module (called re) has a function (named
finditer) that gives you what you want here.
The finditer function will find all matches of a pattern in a string and
return an iterator for them. You can loop through the iterator and do
what you want with each occurrence. import re astring = 'abcd efgd 1234 fsdf gfds abcde 1234' pattern = '1234'
Perhaps just find the starting point of each match:
for match in re.finditer(pat tern,astring):
.... print match.start()
....
10
31
Or the span of each match:
for match in re.finditer(pat tern,astring):
.... print match.span()
....
(10, 14)
(31, 35)
Or use list comprehension to build a list of starting positions:
[match.start() for match in re.finditer(pat tern,astring)]
[10, 31]
And so on ....
Of course, if you wish, the re module can work with vastly more complex
patterns than just a constant string like your '1234'.
Gary Herron
Paul Rubin wrote: mi*******@hotm ail.com writes:
say i have string like this astring = 'abcd efgd 1234 fsdf gfds abcde 1234' if i want to find which postion is 1234, how can i achieve this...? i want to use index() but it only give me the first occurence. I want to know the positions of both "1234"
Most straightforward ly with re.findall -- see the docs.
Not quite. The findall will list the matching strings, not their
positions. -- He'll get ['1234','1234']. The finditer function will
work for his requirements. See my other post to this thread.
I thought this to be a great exercise so I went the extra length to
turn it into a function for my little but growing library. I hope you
enjoy :)
def indexer(string, target):
'''indexer(stri ng, target) ->[list of target indexes]
enter in a string and a target and indexer will either return a
list of all targeted indexes if at least one target is found or
indexer will return None if the target is not found in sequence. indexer('a long long day is long', 'long')
[2, 7, 19]
indexer('a long long day is long', 'day')
[12]
indexer('a long long day is long', 'short')
None
'''
res = []
if string.count(ta rget) >= 1:
res.append(stri ng.find(target) )
if string.count(ta rget) >= 2:
for item in xrange(string.c ount(target) - 1):
res.append(stri ng.find(target, res[-1] + 1))
return res
if __name__ == '__main__':
print indexer('a long long day is long', 'long') # -> [2, 7, 19]
print indexer('a long long day is long', 'day') # -> [12]
print indexer('a long long day is long', 'short') # -> None
Scott David Daniels wrote: mi*******@hotma il.com wrote:
<SNIP> print list(positions( '1234', 'abcd efgd 1234 fsdf gfds abcde 1234'))
prints: [10, 31]
Nicer than mine ;)
Shows I need to get a job where I use python more! This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: kosh |
last post by:
I was wondering if there is or there could be some way to pass a generator an
optional starting index so that if it supported that slicing could be made
more efficient. Right now if you do use a generator and do a or any
other kind of slice it reads all the values up to 100 also.
I know a lot of generators have to do all previous parts...
|
by: Bryan Olson |
last post by:
The Python slice type has one method 'indices', and reportedly:
This method takes a single integer argument /length/ and
computes information about the extended slice that the slice
object would describe if applied to a sequence of length
items. It returns a tuple of three integers; respectively
these are the /start/ and /stop/ indices and...
|
by: Mary |
last post by:
Hi, I need some assistance with a query. To be honest, I'm not even
sure it can be done.
I'll try to keep the information limited to only what's relevant to
what I have and what I am trying to achieve with this query.
I have a table that contains around 100,000 records. For the sake of
this discussion, assume just two columns:
ID Data
|
by: Deniz Bahar |
last post by:
Hello all,
Often times programs in C have arrays used as buffers and shared among
different sections of code. The need arises to have position
indicators to point to different parts of an array (example: point to
top of stack). Before I even got K&R2 I used to just define extra
pointers to types equal to the element type of the arrays to...
|
by: Anjali |
last post by:
Hi,
I am handling an array with a hexadecimal index for the first time.
What actually does the below means.
arr = { '@','£','$','@','@','@','@','@','@','@', 10,'@', 13,'@','@','@',
'@','_','@','@','@','@','@','@','@','@','@', 32,'@','@','@','@',
' ','!','"','#','@','%','&', 39,'(',')','*','+',',','-','.','/',...
| |
by: KK |
last post by:
Dear All
I have an MDI Application which needs to restore it's previously closed
state on subsequent openings.
While closing the application, I am storing the positions of all the Mdi
child windows to a file.While opening I read the positions from the
file,create Mdi Childs and apply positions.
My problem is when I'm recreating the Mdi...
|
by: Anon |
last post by:
Hello All!
I have a long string that I need to make sense out of. I have the
documentation about what info is between which characters, I just need to
somehow parse each 94 character string into it's own section and from there
be able to identify what info is in positions 8-11 or 12-24 etc...
Any thoughts?
TIA
|
by: jmDesktop |
last post by:
This program:
s = 'abcde'
i = -1
for i in range (-1, -len(s), -1):
print s, i
gives
abcd -1
|
by: Henry J. |
last post by:
I have a composite index on two columns in a table. However, the
index is not used in a query that restricts the 2nd column to a
constant. If both columns are linked with columns in other join
tables, the index will be used.
To illustrate it with an example, I have a query like this:
select s.ticker, p.quantity
from stock s, positions...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it. ...
|
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...
| |
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...
|
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...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |