-
#assume that I have a string
-
-
stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
-
-
# I would like to make it
-
stringA = '1$ASD DSA D2$ASFSADSA FSASADSAF 3$AS'
-
#whatever there is 'AS' it should become 'i$AS', where i is its occurrence in the string
-
#how can I do that?
-
12 1181 -
#assume that I have a string
-
-
stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
-
-
# I would like to make it
-
stringA = '1$ASD DSA D2$ASFSADSA FSASADSAF 3$AS'
-
#whatever there is 'AS' it should become 'i$AS', where i is its occurrence in the string
-
#how can I do that?
-
-
>>> stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
-
>>> i = 1
-
>>> resList = []
-
>>> for anStr in stringA.split():
-
... thisItem = ""
-
... mark = 0
-
... n = anStr.count("AS")
-
... for j in range(n):
-
... k = anStr.find("AS")
-
... thisItem += anStr[mark:k] + "%d$AS" %i
-
... i += 1
-
... mark += k + 2
-
... thisItem += anStr[mark:]
-
... if n == 0:
-
... thisItem = anStr
-
... resList.append(thisItem)
-
...
-
>>> resList
-
['1$ASD', 'DSA', 'D2$ASFSADSA', 'FSAFSADSAF', '3$AS']
-
>>> " ".join(resList)
-
'1$ASD DSA D2$ASFSADSA FSAFSADSAF 3$AS'
-
>>>
-
#assume that I have a string
-
-
stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
-
-
# I would like to make it
-
stringA = '1$ASD DSA D2$ASFSADSA FSASADSAF 3$AS'
-
#whatever there is 'AS' it should become 'i$AS', where i is its occurrence in the string
-
#how can I do that?
-
Always more ways than one to skin a cat: -
>>> import re
-
>>> stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
-
>>> marks = re.finditer("AS", stringA)
-
>>> res = ""
-
>>> mark = 0
-
>>> i = 1
-
>>> for m in marks:
-
... res += stringA[mark:m.start()] + "%d$AS" %i
-
... mark = m.end()
-
... i += 1
-
...
-
>>> res
-
'1$ASD DSA D2$ASFSADSA FSAFSADSAF 3$AS'
-
>>>
here is another way: -
stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
-
a=list(stringA)
-
b=[]
-
-
count=1
-
for i in range(len(a)):
-
if a[i]=='A' and a[i+1]=='S':
-
b.append(str(count))
-
b.append('$')
-
b.append(a[i])
-
count +=1
-
else:
-
b.append(a[i])
-
stringA=''.join(b)
-
print stringA
-
bvdet 2,851
Expert Mod 2GB
Nice solutions guys. For the exercise, here's another: - def indexList(s, item, i=0):
-
i_list = []
-
while True:
-
try:
-
i = s.index(item, i)
-
i_list.append(i)
-
i += 1
-
except:
-
break
-
return i_list
-
-
def str_replace_multi(s, tar, sub):
-
"""
-
The target substring is to be replaced by an index
-
number representing its occurrence + '$' + the target.
-
'AS', replaced by i$AS'
-
'sub' must be a string that can be evaluated
-
"""
-
s1 = s
-
indices = indexList(stringA, tar)
-
for i, item in enumerate(indices):
-
item += len(s1)-len(stringA)
-
s1 = ''.join([s1[:max(0,item)], eval(sub), s1[item+len(tar):]])
-
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() :)
And another... with re.
It had to be done! -
import re
-
def repl(match):
-
globals()['count']+=1
-
return '$%i%s'%(globals()['count'],
-
match.groups()[0])
-
-
globals()['count']=0
-
print re.sub('(AS)',repl,stringA)
-
-
>>> $1ASD DSA D$2ASFSADSA FSAFSADSAF $3AS
-
Thank everyone's, especially rhitam30111985;s code
here is another way: -
stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
-
a=list(stringA)
-
b=[]
-
-
count=1
-
for i in range(len(a)):
-
if a[i]=='A' and a[i+1]=='S':
-
b.append(str(count))
-
b.append('$')
-
b.append(a[i])
-
count +=1
-
else:
-
b.append(a[i])
-
stringA=''.join(b)
-
print stringA
-
Thank everyone's, especially rhitam30111985;s code
Which will throw an error if the very last character is an "A".
hey barton u are right .. didnt notice that .. ok how about this? -
stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
-
a=list(stringA)
-
b=[]
-
-
count=1
-
if a[-1]=='A':
-
a.append(' ')# :-P
-
for i in range(len(a)):
-
if a[i]=='A' and a[i+1]=='S':
-
b.append(str(count))
-
b.append('$')
-
b.append(a[i])
-
count +=1
-
else:
-
b.append(a[i])
-
stringA=''.join(b)#while printing, the extra space wont be noticed
-
print stringA
-
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.
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.. :-(
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: -
import re
-
-
stringA = 'ASD DSA DASFSADSA FSAFSADSAF AS'
-
matches = re.finditer("AS", stringA)
-
res = ""
-
mark = 0 # marks where we left off in the string
-
for i, match in enumerate(matches):
-
res += stringA[mark:match.start()] + "%d$AS" %i # or ] + str(i) + "$AS"
-
mark = match.end()
-
-
print res
-
'1$ASD DSA D2$ASFSADSA FSAFSADSAF 3$AS'
And another... with re.
It had to be done! -
import re
-
def repl(match):
-
globals()['count']+=1
-
return '$%i%s'%(globals()['count'],
-
match.groups()[0])
-
-
globals()['count']=0
-
print re.sub('(AS)',repl,stringA)
-
-
>>> $1ASD DSA D$2ASFSADSA FSAFSADSAF $3AS
-
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: -
import re
-
def repl(match):
-
global count
-
count += 1
Yep. I like your way better.
Sign in to post your reply or Sign up for a free account.
Similar topics
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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/>...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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$) {
}
...
|
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...
|
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...
|
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
|
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...
| |