Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
string error
#1
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
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
thanks mate
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020