簡體   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