473,569 Members | 2,400 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

find all index positions

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

May 11 '06 #1
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


May 11 '06 #2

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}

May 11 '06 #3
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
May 11 '06 #4
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
May 11 '06 #5
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.
May 11 '06 #6
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
May 11 '06 #7
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.
May 11 '06 #8
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

May 11 '06 #9

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!

May 11 '06 #10

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

Similar topics

9
2127
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...
108
6336
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...
7
1973
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
4
2332
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...
6
3624
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,'(',')','*','+',',','-','.','/',...
0
1286
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...
4
1261
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
3
1273
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
6
3928
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...
0
7926
Oralloy
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. ...
0
8138
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...
1
7679
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...
0
7983
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...
0
6287
agi2029
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...
0
5223
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...
0
3647
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1228
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
946
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...

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.