[英]How to Change String at Certain Positions From a List
我想知道如何说一个字符串是否在列表中显示的位置上,以便对该字符串做些什么。 让我更好地解释自己。 假设您有一个清单:
positionList = [0,3,6]
现在说您有一个字符串:
exampleString = "Here is a string!"
我怎么能说出如果字符串中的字符在列表中的位置,“例如,'H'在位置0,那么说'H'在位置List中的位置”做某事。
感谢您的时间。 让我知道是否不清楚。 请注意,我正在使用Python 2.7。
编辑-抱歉,我还不够清楚!
我将“ H”与0关联的原因是,如果枚举了它,则它位于字符串的位置0,如下所示:
你好!
0 1 2 3 4 5 6 7 8 9 101112131415
在这里我们可以看到“ Here”中的“ H”位于位置0,“ is”中的“ i”位于位置5,依此类推。
我想知道如何进行如上所述的循环,尽管这根本不是真正的程序语法,但我认为它演示了我的意思:
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.)
让我知道是否不清楚。 再次,我对此表示歉意。
您不能更改原始字符串,而可以直接创建另一个字符串:
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
“她是一根绳子!”
字符串在Python中是不可变的,因此要进行更改,您必须首先复制它,并且在完成更改后必须将其复制回来。 例:
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.