簡體   English   中英

And_index應該輸出and的索引,但是輸出奇怪的東西

[英]And_index should print indexes of and, but outputs weird things

是的,我不擅長這樣做。 And_index在輸入中應具有打印的索引“ and”。

def ask():
  x = input("Enter your logical operation:")
  return list(map(str.upper, x.split()))

user_input = ask()

and_index = []


for i in range(0,len(user_input)):

  and_index.append(user_input.index("AND",i))
  and_index = list(set(str(and_index)))




print(and_index)

輸入:1和1輸出:1(輸入列表的索引和索引)實際輸出:['[','','0',“'”,']','1',',']

在這種情況下,輸入為:和

從您的問題中還不清楚您到底要達到什么目標。 但是,似乎您想獲取主字符串中某個子字符串的索引。 下面是一個通用函數,它將獲取一個字符串和一個子字符串,並返回給您一個找到子字符串的起始索引列表

def get_indexes_of_substring(input_string: str, substring: str) -> list:
    i = 0
    indexes = []
    while i < len(input_string):
        try:
            index = input_string.index(substring, i)
            indexes.append(index)
            i = index + len(substring)
        except ValueError as ve:
            break
    return indexes

user_input = "lowercase and, uppercase AND, mixedcases anD aND And ANd AnD aNd"
substring = "AND"
indexes_of_substring = get_indexes_of_substring(user_input.upper(), substring)

print(f'we found {len(indexes_of_substring)} instances of {substring}. These can be found at the following indexes:')
substring_len = len(substring)
for index in indexes_of_substring:
    end = index + substring_len # Note end is actually the index after the end of the word so it works with slices
    print(f'index: [{index}:{end}], word: {user_input[index:end]}')

輸出值

we found 8 instances of AND. These can be found at the following indexes:
index: [10:13], word: and
index: [25:28], word: AND
index: [41:44], word: anD
index: [45:48], word: aND
index: [49:52], word: And
index: [53:56], word: ANd
index: [57:60], word: AnD
index: [61:64], word: aNd

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM