变量的索引赋值

index assignment to a variable

我是编程新手,最近开始学习字符串和循环。我想知道是否可以将字符串中的任何字母表的索引分配给变量

def max_char(a_string):
val="abcdefghijklmnopqrstuvwxyz"
counter=0
for i in range (len(val)):
   for k in range(len(a_string)):
      if val[i] == a_string[k]:
        if counter==0:
         x1=val.index(i)  #here I want to assign the index of ith element of val to x1. Also tried *x1=val[i].index*
         counter=1

您可以使用您在循环中声明的索引本身来分配它。

x1=i #This is the index of val in that iteration.

在这种情况下,此代码将 return a_string 的第一个元素,该元素也在 val 中.

只需分配给 i

def max_char(a_string):
    val = "abcdefghijklmnopqrstuvwxyz"
    counter = 0
    for i in range(len(val)):
        for k in range(len(a_string)):
            if val[i] == a_string[k]:
                if counter == 0:
                    x1 = i  # here I want to assign the index of ith element of val to x1. Also tried *x1=val[i].index*
                    counter = 1
                    print(x1)


max_char("s")
Output: 18