very good I was creating a test code for an exercise, but I could not achieve it. The idea is that it takes the first number as the start of a subString and the second its length. Something like this for example: phrase: 'Developing' num1: 4 num2: 8 output: rolland
print("Escoga dos numeros y una frase")
posicion = input("Introduzca el primero numero: ")
longitud = input("Introduzca el segundo numero: ")
frase = input("Introduzca una frase: ")
sub_frase = frase[int(posicion):longitud]
print(sub_frase)
input()
What happens is that the value you take from the default user keyboard input is a string. If you try to access a range of the stringfrase
with those strings it will give the following error:I can think of three ways to fix it:
1. Evaluating the
input()
withint
:In this way the function is applied
int()
on the input, this functionint()
returns the literal integer type of a string (if it is valid). So when the range is invoked it will be done with integers.2.Invoking the range with the integer literals:
The same function
int()
can be applied when the range of the string in question is to be invoked, taking theinput()
as string.Evaluating with
ast.literal_eval()
(more literals):You can evaluate the range of the string in question with string variables, by means of the
literal_eval()
module functionast
:Solution to your problem:
Of the three ways that I exemplified with the first one, it should already work well: (I don't even know why I put the others xDDDDD):
Execution:
I hope it has served you, greetings!
The function
input
always returns a class objectstr
. If what you require are valuesint
to be used in another operation (as in this case) you have to do a casting (that is, convert it to another data type):The
num2+1
is because index-slicing reduces the scope of the range by one position.