473,385 Members | 1,409 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

manipulating string question

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 1181
bartonc
6,596 Expert 4TB
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 Expert 4TB
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 100+
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 Expert Mod 2GB
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_multi(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
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
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 Expert 4TB
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 100+
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 Expert 4TB
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
rhitam30111985
112 100+
yep.. it will contain the extra chcracter.. which is just a space... so not really a problem we can put a check at the end for the last character if it is a space.. then we can use the list.pop() or list.remove() method to get rid of it... .. as for regular expressions.. i personally stay away from them.... they r just beyond my comprehension.. :-(
Oct 12 '07 #11
bartonc
6,596 Expert 4TB
yep.. it will contain the extra chcracter.. which is just a space... so not really a problem .. as for regular expressions.. i personally stay away from them.... they r just beyond my comprehension..
This (slightly simplified) one seems pretty basic:
Expand|Select|Wrap|Line Numbers
  1. import re
  2.  
  3. stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
  4. matches = re.finditer("AS", stringA)
  5. res = ""
  6. mark = 0  # marks where we left off in the string
  7. for i, match in enumerate(matches):
  8.     res += stringA[mark:match.start()] + "%d$AS" %i  # or ] + str(i) + "$AS"
  9.     mark = match.end()
  10.  
  11. print res
  12. '1$ASD DSA D2$ASFSADSA FSAFSADSAF 3$AS'
Oct 12 '07 #12
bartonc
6,596 Expert 4TB
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.  
Let Python search for the variable outside the scope of the function instead of returning the dictionary reference (just thinking out loud, here)... I think I really like your way. Just for completeness, I'll post to see how it looks:
Expand|Select|Wrap|Line Numbers
  1. import re
  2. def repl(match):
  3.     global count
  4.     count += 1
Yep. I like your way better.
Oct 12 '07 #13

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

Similar topics

4
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...
12
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...
3
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...
5
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...
2
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...
8
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...
4
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/>...
0
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...
1
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.