-
#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 1209 bartonc 6,596
Recognized Expert Expert -
#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'
-
>>>
bartonc 6,596
Recognized Expert Expert -
#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
Recognized Expert Moderator Specialist
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_mul ti(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
-
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".
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
-
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.
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 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:
|
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
|
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...
|
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...
|
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.
| |
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.
|
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">
|
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"/>
|
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"
|
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...
|
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...
| |
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...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
|
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |