Python Forum

Full Version: string error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hey guys, I am new to python programming. I was practising a program that prints first half of a string. But I cant run the code. please identify the error I am making
str=input("enter any string")
length=(len(str))
if length%2==0:
    length=len(str)
    half=str[0:length/2]
    print(half)
else:
    print("input even no. string")
Above code is giving me following error in line number 5 in pycharm
--Special Variable
--length={int}6
--str={str}computer

What am I doing wrong
true division always returns float, so length / 2 returns float which is not allowed as index. use floor division length // 2

also don't use str as variable name . it's a type and you overshadow it, i.e. you will not be able ti use it if needed

my_str = 'foo'
print(isinstance(my_str, str))
str = 'bar'
print(isinstance(my_str, str))
Output:
True <-- this is first print Traceback (most recent call last): File "************", line 4, in <module> print(isinstance(my_str, str)) TypeError: isinstance() arg 2 must be a type or tuple of types
thanks mate