如何从索引中获取字符串

how to get string from index

我想知道如何从索引中获取字符串。

例如:

这是我的代码。它没有给我正确的价值。如果有人可以提供帮助,那将很有用。 (我是 Python 的初学者)

import math 
user_input1 = input("Your chosen number: ")

number_pick = input(" Num?")

value_of_pick1 = user_input1.find(number_pick)

value1 = user_input1[value_of_pick1]

print("Value: ", value1)

问题是在列表中索引从 0 而不是 1 开始。所以这应该给你想要的结果:

value_of_pick1 = user_input1.find(number_pick - 1)

试试这个:

user_input1 = input("Your chosen number: ").split()
number_pick = input(" Num?")
print("Value: ", user_input1[int(number_pick)-1]) #index starts at 0

您可以将 number_pick 解析为 int

而不是使用 find()

我将使用 str.split() 方法,它只需要一个 stringsplits 给定的分隔符。

user_input = input("Your chosen number: ").split(' ')
# I use .split(' ') to make '5 4 4 6 1' into ['5', '4', '4', '6', '1']
# Because now it will be easier to index it

number_pick = int(input("Num: "))
# If we enter 4, this will be the integer 4, not '4'

# And now we just take the element with our index - 1,
# because lists are zero-indexed
value = user_input[number_pick - 1]

print("Value: {}".format(value))  # Value: 6

在 运行 这个代码之后:

>>> Your chosen number: 5 5 4 6 1
['5', '4', '4', '6', '1']
>>> Num: 4
4

Value: 6

而且我认为 math 对于这段代码来说是多余的。

split()用法说明:

当我们为 user_input 变量输入 5 4 4 6 1 时,它的值只是字符串 "5 4 4 6 1".

当我们对其执行 .split(' ') 时,它会创建一个列表,其中包含我们的值,由 " " 分隔。

所以在拆分之后,我们有 ['5', '4', '4', '6', '1']。有关详细信息,请参阅 the docs

您误解了 stringfind 选项的性质以及它 returns 索引的想法,具有 list.
find判断字符串str是否出现在string中returns它的indexstring
str的起点 所以:

>>> a="now is the winter"
>>> a.find("winter")
11

单词"winter"存在于a中,从位置11开始(从位置0开始)
在你的情况下:

>>> a="5 5 4 6 1"
>>> a.find("4")
4

是正确答案。

对此进行扩展,您可以操纵来自 find

的索引结果
>>> a="now is the winter of our discontent, made glorious Summer by this Son of York"
>>> f="winter"
>>> x = a.find(f)
>>> a[x:]
'winter of our discontent, made glorious Summer by this Son of York'
>>> a[x:len(f)+x]
'winter'

最好 运行 将其转换为列表的答案,因为这似乎是您真正想要做的。

您可以使用此代码而不是使用 Find.

来实现相同的目的
user_input1 = input("Your chosen number: ").split() 
#spliting input into list

number_pick = int(input(" Num?")) 
#explicitly converting into integer

user_input1_tolist = [int(i) for i in user_input1] 
#using list comprehension to convert into list

value1 = user_input1_tolist[number_pick] 
#index starting from zero

print("Value: ", value1)