user163505
user163505

Reputation: 499

How to Change String at Certain Positions From a List

I would like to know how to say if a string is at a position shown in a list, to do something to that string. Let me explain myself better. Say you have a list:

positionList = [0,3,6]

Now say you have a string:

exampleString = "Here is a string!"

How would I be able to say that if a character in the string is at a position that is in the list, "e.g., 'H' is at position 0, so saying that since 'H' is at a position that is in positionList" to do something to it.

Thank you for your time. Let me know if I'm not being clear. Please note that I am using Python 2.7.

EDIT-It appears I'm not being clear enough, my apologies!

The reason I associate "H" with 0 is because it is at position 0 in the string if it were enumerated, like so:

H e r e i s a s t r i n g !

0 1 2 3 4 5 6 7 8 9 101112131415

Here we can see that "H" in "Here" is at position 0, "i" in "is" is at position 5, and so on.

I want to know how to make a loop as described above, while this isn't real program syntax at all, I think it demonstrates what I mean:

loop through positions of each character in enumerated string:

      if position is equal to a number in the positionList (i.e. "H" is at 0, and since 0 is in positionList, it would count.):

          Do something to that character (i.e. change its color, make it bold, etc. I don't need this part explained so it doesn't really matter.)

Let me know if I'm not being clear. Again, my apologies for this.

Upvotes: 0

Views: 115

Answers (2)

lenik
lenik

Reputation: 23508

you cannot change the original string, you may just created another off it:

pos = [0, 3, 6]
str = 'Here is a string'

def do_something( a ) :
    return a.upper()

new_string = ''.join( [do_something(j) if i in pos else j for i,j in enumerate(str)] )

print new_string

'HerE iS a string!'

Upvotes: 1

pts
pts

Reputation: 87221

Strings are immutable in Python, so to make changes you have to copy it first, and you have to copy back after having done the changes. Example:

 exampleString = "Here is a string!"
 positionList = [0,3,6]

 import array
 a = array.array('c', exampleString)
 for i in positionList:
   a[i] = a[i].upper()
 exampleString = a.tostring()
 print exampleString

Upvotes: 0

Related Questions