Home > Software design >  TypeError: must be str, not int in python code
TypeError: must be str, not int in python code

Time:09-22

def _count(name):
    print (name.count(0, len(name)))

_count('saber')

I'm trying to write this code where i can count the number of the given string but ending up getting this error:

PS C:\Users\soubh> & D:/python/python.exe d:/imp/demo1.py
Traceback (most recent call last):
  File "d:\imp\demo1.py", line 57, in <module>
    _count('saber')
  File "d:\imp\demo1.py", line 55, in _count  
    print (name.count(0, len(name)))
TypeError: must be str, not int

I'm new at python so please help out with any solution using count method as well as native method and please do explain both approaches will be helpful.

CodePudding user response:

I'm not sure what exactly you're trying to achieve but I can tell you're trying to use the count method.

You can only use the count method when you have two strings (Based on this page by w3c).

If you want to count the amount of a given string, say 's' appears in 'saber':

name = 'saber'
name.count('s', 0, len(name))

If you want to get the length of a given string, use the len function:

len(name)

EDIT:

If you want to implement the count function on your own, you can loop through each letter and increment a counter if the letter matches the one you want, e.g.:

def _count(word,letter):
  frequency = 0
  for l in word:
    if l == letter:
      frequency  = 1
  return frequency

_count('saber','s')

CodePudding user response:

This is a better way to do this and it shows no errors.

def length(name):
    print(len(name))
length("hi")
  • Related