简体   繁体   English

如何从列表的某些位置更改字符串

[英]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. 我怎么能说出如果字符串中的字符在列表中的位置,“例如,'H'在位置0,那么说'H'在位置List中的位置”做某事。

Thank you for your time. 感谢您的时间。 Let me know if I'm not being clear. 让我知道是否不清楚。 Please note that I am using Python 2.7. 请注意,我正在使用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”与0关联的原因是,如果枚举了它,则它位于字符串的位置0,如下所示:

H ereisastring ! 你好!

0 1 2 3 4 5 6 7 8 9 101112131415 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. 在这里我们可以看到“ Here”中的“ H”位于位置0,“ is”中的“ i”位于位置5,依此类推。

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. 字符串在Python中是不可变的,因此要进行更改,您必须首先复制它,并且在完成更改后必须将其复制回来。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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