hi guys

is there a way to refer to every 2nd symbol of a string?

example:

mystring = 'bananasplit'

i want to refer to every 2nd and every 3rd symbol of any string the user types in.

in this case the 1st symbol is 'b', the 2nd is 'a', the 3rd is 'n' ... and then it starts counting again -> 1st is 'a', second is 'n', 3rd is 'a', then it starts counting again ... and so on ...

is there a way to change every 2nd symbol to 'x' and every 3rd symbol to 'y' - the first symbol should be left as it is

how can i refer to every 2nd / 3rd symbol (not knowing the string)

Thanks in advance

Greetz

Hint, generally you iterate over the string like this:

mystring = "abcdefghijklmnop"

# newstring starts as an empty string (no char in it)
newstring = ""
count = 0
for c in mystring:
    # every third character is added to newstring
    if count % 3 == 0:
        #print( c )  # test
        # build up newstring
        newstring += c
    # increment count by 1
    count += 1

print( newstring )  # adgjmp

This will change every 2nd letter to "x" and every 3rd letter to "y", but note that the 6th letter could become either "x" or "y" depending on the logic.

def change_chr(chr, x):
   if not x % 3:
      return "y"
   if not x % 2:
      return "x"
   return chr
   
mystring = 'bananasplit'
result = [change_chr(mystring[x], x+1) for x in range(len(mystring))]

print "".join(result) 

##prints bxyxnysxyxt
Member Avatar for masterofpuppets

hi,
here's my version of this:

s = "bananasplit"   
newS = ""

for e in range( 0, len( s ), 3 ):
    newS += s[ e:e + 3 ][ 0 ]
    if len( s[ e:e + 3 ] ) == 3:
        newS += "xy"
    elif len( s[ e : e + 3 ] ) == 2:
        newS += "x"

print newS
# -> >>> 
bxyaxysxyix
>>>

Note that since the last symbol is 11th only x is added at the end

hope this helps :)

I couldn't resist having a go as well. The way I have done it makes it easy to change, say to every forth value and add three letters in. You also have no issue of over running the values:

string_thing , di, Fi, z = (raw_input("Enter a string thing\n-->"),[], [], 0)

for a in range(len(string_thing)):
    di.append(string_thing[a])  # Create list of letters

while z < len(di):
    Fi.append(di[z])  # Just get rid of the values we don't want
    z = z + 3


print "xy".join(Fi)  # and just stick it all in afterwards

I couldn't resist playing with it a little and thought it might make an interesting string module, to which a number of methods could be added. Something like this

class NthStrFiller:
    """change every 2nd symbol to 'x' and every 3rd symbol to 'y' -                 
       the first symbol should be left as it is.
       The sequence can be changed and so can the filler"""
    def __init__(self, string_thing, nth=3, glueStr='xy'):   
        self.string_thing = string_thing
        self.nth = nth
        self.glue = glueStr
    def PrintIt(self):
        """Print it out"""
        di, Fi, z = ([],[],0)
        for a in range(len(self.string_thing)):
            di.append(self.string_thing[a])  # Create list of letters
        while z < len(di):
            Fi.append(di[z])  # Just get rid of the values we don't want
            z = z + self.nth
        print self.glue.join(Fi)  # and just stick it all in afterwards

if __name__ == "__main__":
    fun = NthStrFiller("bananastring")
    fun.PrintIt()

Nice solutions, thanks you all...

... but I guess that's not exactly what I need. Probably I have to get more specific:

list_all = [
['A', 'B', 'C', 'D']
['E', 'F', 'G', 'H']
['I', 'J', 'K', 'L']
]
mystring = 'bananasplit'

for i in range(len(mystring)):
    letter = mystring[i]
for j in range(3):
   list_change = list_all[j][0]
   list_all[j].remove(list_change)
   list_all[j].append(list_change)

Okay, look.

I want to remove and append the actual element at position 0 of the actual list.

The 1st list (list_all[0]) should be changed for every character in mystring.
The 2nd list (list_all[1]) should be changed for every second character.
The 3rd list (list_all[2]) should be changed for every third charakter in mystring.

->
'bananasplit'
'b' should change only the first list.
'a' should change the first AND the second list.
'n' should change the first AND the third list.
'a' should only the first list.
'n' should change the first AND the second list.
'a' should change the first AND the third list.
's' should change only the first list

... and so on - I hope u get the idea.

My code obviously changes every list for every character in mystring.
How do I implement that thing above?

Thanks in advance.

It's the same principle but using a function that knows the beginning point and how many letters to skip. You send the first list to the function with start_at = first letter, and skip =1 since you want to change every letter. You then send the second list with start_at = 1 or 2 depending on if you start counting with zero or one and skip = 3. The third list would start with 2 or 3 and skip 3, etc.

Sorry, wooee, but I don't get what you mean by that ... :-(

What exactly do you need? The goal seems to be changing all the time.

That's what I want.
I want the lists to change for every character of the string BUT! the 2nd list only should change with every 2nd character of the string (which means:
string[0] changes list 1 only
string[1] changes list 1 and 2
string[2] changes list 1 and 3
string[3] changes list 1 only again
string[4] changes list 1 and 2
string[5] changes list 1 and 3
string[6] changes list 1 only
string[7] changes list 1 and 2
and so on...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.