473,811 Members | 3,290 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

manipulating string question

90 New Member
Expand|Select|Wrap|Line Numbers
  1. #assume that I have a string
  2.  
  3. stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
  4.  
  5. # I would like to make it
  6. stringA = '1$ASD DSA D2$ASFSADSA FSASADSAF 3$AS'
  7. #whatever there is 'AS' it should become 'i$AS', where i is its occurrence in the string
  8. #how can I do that?
  9.  
Oct 11 '07 #1
12 1209
bartonc
6,596 Recognized Expert Expert
Expand|Select|Wrap|Line Numbers
  1. #assume that I have a string
  2.  
  3. stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
  4.  
  5. # I would like to make it
  6. stringA = '1$ASD DSA D2$ASFSADSA FSASADSAF 3$AS'
  7. #whatever there is 'AS' it should become 'i$AS', where i is its occurrence in the string
  8. #how can I do that?
  9.  
Expand|Select|Wrap|Line Numbers
  1. >>> stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
  2. >>> i = 1
  3. >>> resList = []
  4. >>> for anStr in stringA.split():
  5. ...     thisItem = ""
  6. ...     mark = 0
  7. ...     n = anStr.count("AS")
  8. ...     for j in range(n):
  9. ...         k = anStr.find("AS")
  10. ...         thisItem += anStr[mark:k] + "%d$AS" %i
  11. ...         i += 1
  12. ...         mark += k + 2
  13. ...         thisItem += anStr[mark:]
  14. ...     if n == 0:
  15. ...         thisItem = anStr
  16. ...     resList.append(thisItem)
  17. ...     
  18. >>> resList
  19. ['1$ASD', 'DSA', 'D2$ASFSADSA', 'FSAFSADSAF', '3$AS']
  20. >>> " ".join(resList)
  21. '1$ASD DSA D2$ASFSADSA FSAFSADSAF 3$AS'
  22. >>> 
Oct 11 '07 #2
bartonc
6,596 Recognized Expert Expert
Expand|Select|Wrap|Line Numbers
  1. #assume that I have a string
  2.  
  3. stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
  4.  
  5. # I would like to make it
  6. stringA = '1$ASD DSA D2$ASFSADSA FSASADSAF 3$AS'
  7. #whatever there is 'AS' it should become 'i$AS', where i is its occurrence in the string
  8. #how can I do that?
  9.  
Always more ways than one to skin a cat:
Expand|Select|Wrap|Line Numbers
  1. >>> import re
  2. >>> stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
  3. >>> marks = re.finditer("AS", stringA)
  4. >>> res = ""
  5. >>> mark = 0
  6. >>> i = 1
  7. >>> for m in marks:
  8. ...     res += stringA[mark:m.start()] + "%d$AS" %i
  9. ...     mark = m.end()
  10. ...     i += 1
  11. ...     
  12. >>> res
  13. '1$ASD DSA D2$ASFSADSA FSAFSADSAF 3$AS'
  14. >>> 
Oct 11 '07 #3
rhitam30111985
112 New Member
here is another way:
Expand|Select|Wrap|Line Numbers
  1. stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
  2. a=list(stringA)
  3. b=[]
  4.  
  5. count=1
  6. for i in range(len(a)):
  7.     if a[i]=='A' and a[i+1]=='S':
  8.         b.append(str(count))
  9.         b.append('$')
  10.         b.append(a[i])    
  11.         count +=1
  12.     else:
  13.         b.append(a[i])
  14. stringA=''.join(b)
  15. print stringA
  16.  
Oct 11 '07 #4
bvdet
2,851 Recognized Expert Moderator Specialist
Nice solutions guys. For the exercise, here's another:
Expand|Select|Wrap|Line Numbers
  1. def indexList(s, item, i=0):
  2.     i_list = []
  3.     while True:
  4.         try:
  5.             i = s.index(item, i)
  6.             i_list.append(i)
  7.             i += 1
  8.         except:
  9.             break
  10.     return i_list
  11.  
  12. def str_replace_multi(s, tar, sub):
  13.     """
  14.     The target substring is to be replaced by an index
  15.     number representing its occurrence + '$' + the target.
  16.     'AS', replaced by i$AS'
  17.     'sub' must be a string that can be evaluated
  18.     """
  19.     s1 = s
  20.     indices = indexList(stringA, tar)
  21.     for i, item in enumerate(indices):
  22.         item += len(s1)-len(stringA)
  23.         s1 = ''.join([s1[:max(0,item)], eval(sub), s1[item+len(tar):]])
  24.     return s1
>>> stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
>>> str_replace_mul ti(stringA, 'AS', "'%d$AS' % (i+1)")
'1$ASD DSA D2$ASFSADSA FSAFSADSAF 3$AS'
>>>

I keep finding uses for function indexList() :)
Oct 11 '07 #5
rogerlew
15 New Member
And another... with re.
It had to be done!

Expand|Select|Wrap|Line Numbers
  1. import re
  2. def repl(match):
  3.     globals()['count']+=1
  4.     return '$%i%s'%(globals()['count'],
  5.                     match.groups()[0])
  6.  
  7. globals()['count']=0 
  8. print re.sub('(AS)',repl,stringA)
  9.  
  10. >>> $1ASD DSA D$2ASFSADSA FSAFSADSAF $3AS
  11.  
Oct 12 '07 #6
python101
90 New Member
Thank everyone's, especially rhitam30111985; s code

here is another way:
Expand|Select|Wrap|Line Numbers
  1. stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
  2. a=list(stringA)
  3. b=[]
  4.  
  5. count=1
  6. for i in range(len(a)):
  7.     if a[i]=='A' and a[i+1]=='S':
  8.         b.append(str(count))
  9.         b.append('$')
  10.         b.append(a[i])    
  11.         count +=1
  12.     else:
  13.         b.append(a[i])
  14. stringA=''.join(b)
  15. print stringA
  16.  
Oct 12 '07 #7
bartonc
6,596 Recognized Expert Expert
Thank everyone's, especially rhitam30111985; s code
Which will throw an error if the very last character is an "A".
Oct 12 '07 #8
rhitam30111985
112 New Member
hey barton u are right .. didnt notice that .. ok how about this?

Expand|Select|Wrap|Line Numbers
  1. stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
  2. a=list(stringA)
  3. b=[]
  4.  
  5. count=1
  6. if a[-1]=='A':
  7.     a.append(' ')# :-P
  8. for i in range(len(a)):   
  9.     if a[i]=='A' and a[i+1]=='S':
  10.         b.append(str(count))
  11.         b.append('$')
  12.         b.append(a[i])    
  13.         count +=1
  14.     else:
  15.         b.append(a[i])
  16. stringA=''.join(b)#while printing, the extra space wont be noticed 
  17. print stringA
  18.  
Oct 12 '07 #9
bartonc
6,596 Recognized Expert Expert
hey barton u are right .. didnt notice that .. ok how about this?
Yep. That would do it. But wouldn't the result contain the extra character?

I still like my Regular Expression method best.
Oct 12 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

4
22942
by: Michael J. Astrauskas | last post by:
Does anyone have a function for manipulating GET variables in a URL? I want to be able to modify some parameters without affecting others. An example of what I'm looking for: Let's say the current url is: www.mine.com/home.php?name=joe&page=7&theme=blue I want to be able to run a function like: $newurl = change_get($_SERVER,"page","6"); and end up with:
12
5249
by: Kin®sole | last post by:
Hi I'm very new to VB (using VB6) I have two lists one blank and one containing names in the format of surname and then forename.I also have a combo box containing forenames.When I select a forename from my combo box I need to add the corresponding surname into the blank list box.What is the best way to do this? hope this make sense TIA
3
2665
by: da Vinci | last post by:
OK, this is a pretty weird question, but shouldn't be to hard to accomplish. Remember, I am a beginner so please, if I say something stupid, be gentle. :-) I do not know vectors yet, which would probably be a better idea than an array for this, but I want to try using an array for now and then will update it once I learn vectors. I havent really learned arrays yet either.... :-) So here it is.... I want to read in a string of...
5
13758
by: Veit Wiessner | last post by:
I wrote a program that handles the buildcount of projects (gets called every time I compile a project, it writes a header file which is #include-ed in the project). My question is this, is it possible to modify string constants with preprocessor macros? for now I write every string I need as a #define in the generated header, when in theory I only need to define the buildcount there and put it then in the places where I need it. for...
2
1424
by: Gary Wessle | last post by:
Hi Stroustrup p.312 second paragraph after the code. " To get polymorphic behavior in C++, the member function called must be virtual and objects must be manipulated through pointers or references." the code below fulfills the virtual part, can someone please show me how the second part is done? i.e, manipulating the object through pointers or references.
8
13065
by: brainflakes.org | last post by:
Hi guys, I need to manipulate binary data (8 bit) stored in a 2 dimensional array. I've tried various methods (arrays, using a string filled with chr(0), using gd lib) and so far the fastest way I've found is to actually create an 8-bit image in GD and use imagecolorat and imagesetpixel to read and write the data.
4
2738
by: GoguLKS | last post by:
Hi, I am trying to manipulate a XSLT variable. Manipulating is replacing the string value in it. My XML file looks like: <root> <item name="PageTitle"> <value>Screen Page<value/> </item> <item name="PageHeader">
0
1713
by: lehu | last post by:
Hi, I have created web service, it's practically finished, but I wanted to do some improvements in generated wsdl: - For string parameters i get element tag such as this in wsdl: <s:element minOccurs="0" maxOccurs="1" name="xml" type="s:string"/> 1.) For some of those parameters i want to make it mandatory, changing minOccurs to 1: <s:element minOccurs="1" maxOccurs="1" name="xml" type="s:string"/>
1
7210
by: Stephen Cattaneo | last post by:
Hi all, I am relatively new to socket programming. I am attempting to use raw sockets to spoof my IP address. From what I can tell I will have to build from the Ethernet layer on up. This is fine, but I am having some trouble with manipulating my hex values. Seems to me that there are two ways to store hex values: 1. as literal hex - 0x55aa 2. as a string - "\x55aa"
0
10647
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10384
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...
0
10130
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...
0
9204
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6887
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5692
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4338
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
3865
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3017
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.