Python основы - квадратные скобки - PullRequest
0 голосов
/ 16 марта 2020

Я в начале пути к коду. Я начал изучать код самостоятельно. Я ищу помощь с программой Basi c python. Моя цель - создать программу basi c, в которой:

  • есть фрагмент текста длиной 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])

Моя задача - поместить переменную в квадратную скобку. К сожалению, это не работает. Я знаю, что проблема начинается с двух последних строк кода.

Я не ищу готового решения. Я хотел бы попросить вас показать мне, как решить эту проблему. Большое спасибо!

Ответы [ 2 ]

1 голос
/ 16 марта 2020

Это должно работать:

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)

0 голосов
/ 17 марта 2020

Спасибо @Клаус Д. Понял:

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!')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...