[英]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.