繁体   English   中英

Python 基础——方括号

[英]Python basics - square brackets

我正处于编码之路的起点。 我已经开始自学代码了。 我正在寻求有关基本 python 程序的帮助。 我的目标是创建基本程序,其中:

  • 有一段文字 10 个字符长
  • 程序要求选择 0-9 之间的数字
  • 程序返回等于使用该程序的人选择的数字的字母。

为了简化它:

  • 文本:示例文本:请选择数字0-9
  • 答案:5
  • 返回:e

这是我的一段代码:

text = "Let's check"
text1 = text
print(text)
digit = input('Choose digit between 0-9')
print(int(digit))
print(text1[digit:6])

我的问题是将变量放入方括号中。 不幸的是它不起作用。 我知道问题始于代码的最后两行。

我不是在寻找现成的解决方案。 我想请你告诉我如何解决它。 非常感谢你!

这应该有效:

int_digit = int(digit)
print(int_digit) # not necessary, leave this if you want to print the user input as an integer
print(text1[int_digit-1])

这里没有太多解释,这就是python的工作原理。

最后需要-1 ,因为此函数按索引(从 0 开始)抓取

我对 Python 和一般编程很陌生,但这就是我解决问题的方法:

letter = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
digit = int(input())
print(letter[digit])

我会尽量把它说得简单点:

text = "Let's check"
digit = int(input("Choose a digit between 0 and 9: "))
letter = text[digit]  # The index [digit] is basically the digit entered at the line above
print(letter)

谢谢@Klaus D. 是这样理解的:

print('Hello! Below you can find piece of text:')
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eu lacinia velit. Quisque a ante eu metus ullamcorper sagittis. Phasellus nec varius nibh. Cras maximus mauris vel vehicula congue. Morbi nibh tellus, convallis a sollicitudin in, tincidunt vel elit. Cras tincidunt massa metus, scelerisque luctus sapien laoreet in. Suspendisse rutrum dolor vitae neque semper, sed pulvinar felis feugiat. Morbi et aliquam lorem. Quisque nec arcu varius, iaculis nulla eget, vestibulum diam. Nam volutpat felis et sapien porta lobortis."
text1 = text
print(text1)
print('Want to check what is hidden in the text above? Please follow the instructions!')
digit_beg = input('Choose digit between 0-500')
digit_end = input('Choose digit between 0-500 (no smaller than first one)')
digit1 = (int(digit_beg))
digit2 = (int(digit_end))
print('!!!The digits you have chosen are the numbers of following letters in the text. Below you can find is included between letters you have chosen by indicating specific digits.')
print(text1[digit1:digit2])
print('Thank you!')
text = "Let's check"  # here index numbers are (L=0, e=1, t=2, '=3, s=4, blank space=5, c=6, h=7... so on)
text1 = text
print(text)
digit = int(input('Choose digit between 0-9:  '))
letter = text[digit]  # you can also put text as text1 coz text = text1
print(letter)

看到你可以接受从 0 到 9 的输入并想要打印出现在 integer position 的字母表为此你必须列出一个列表,其中应该有第一个字母表到第 10 个字母表然后如果你想打印用户定义的字母然后你必须像这样给 output..

a=int(input("Enter the place value of the alphabet ranging from 0 to 9: "))
b=['a','b','c','d','e','f','g','h','i','j']
print(a[b])#this will print the output here b is the list and a is the user input in integer form

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM