简体   繁体   中英

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, "eg, '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 ereisastring !

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.

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!'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM