'str' object is not applicable - python

I have the following little function written in Python:
def encode(str):
out = ""
for i in str:
ret += str(ord(i.upper()) - 64)
return ret
Basically, what I want to do is get the number of the letter in the alphabat and concatenate it to the 'out' string. With this code I get a traceback at line 4: 'str' object is not applicable.
Could someone please explain me why it throws this error and how I can fix this? (Sorry if this was already asked once, I couldn't find it, probably also because I'm pretty new to Python and programming)

Never name your variable on the pre-defined built-in name.
In your code, str is not a built-in function. It's the variable you have used as parameter in your function.
Another problem is, you have declared out variable, and using ret which will give you error. Change out = "" to ret = "".

Don't call your variable str, you're shadowing the built-in function.
Also, you need to fix the naming of out/ret.
I personally would write this function as follows:
def encode(s):
return ''.join(str(ord(c.upper()) - 64) for c in s)
(I don't really follow what the str(ord(...)) is meant to be doing, so I've just copied it from your code.)

As the others have said, do not use str as a variable.
I suspect this is what you want though:
def encode(s):
return "".join(chr(ord(c.upper()) - 64) for c in s)
This is equivalent to:
def encode(s):
out = ""
for c in s:
ret += chr(ord(c.upper()) - 64)
return ret
You were looking for the chr() function, which converts a numerical ASCII/Unicode value into a 1-character string. Running str() would convert 5 to "5".
Also on a stylistic note, it's customary to do for c in s when iterating over a string, and for i in x when iterating over a sequence of integers.

Related

I'm struggling to concatenate a string to a function

This is my code. Solution #1:
def age():
input('Age: ')
def friends():
print("John" + age)
Expected outcome:
John13
Actual outcome #1:
TypeError: can only concatenate str (not "function") to str
Solution #2:
def age():
input('Age: ')
def friend():
print("John" + age())
Solution outcome #2:
TypeError: can only concatenate str (not "NoneType") to str
How can I concatenate my function age (age is an input() function declaration) to a string or strings? The age function is an input() and I want to add it to the appropriate name or string.
You need to add a return statement to your function age, for example:
def age():
agein = input(...)
return agein
age() doesn't do anything with the input, it just throws it away immediately. You need to actually return the value.
Also, there's little point in creating a method that does nothing but call another method. Why not just call input(...) "directly"?
Also, your first solution does not concatenate the string returned by age - without the (), you try to append the age() method itself to the string, which doesn't make sense.
As you know, the variable age as you've defined it is a function, not a string.
So your question boils down to:
How can we extract the actual data we want -- in this case, a string representing an age -- from
our function?
In other words,
How can we make our function "return" the data we want?
Simple! There is a construct in Python (and just about every other programming language) that does exactly this!
It is called a return statement. It "returns" a value -- any value you want -- from a function, which simply means that your code outside the function may use that value.
For example:
def age():
age = input('Age: ')
return age // We can now use this value outside the function!
You can use it like so:
def friends():
johns_age = age() // calling the age function and assigning its returned value
print("John is " + johns_age)
If you found this answer helpful, I suggest you read a beginner-friendly Python book (such as the free Automate the Boring Stuff with Python), as you'll learn much faster that way than asking questions on this rather strict and unfriendly site.

How to use counter variable inside the body of recursive function

Below the code for counting the no of '1' character in String.
count2=0 #global variable
def Ones(s):
no=0;
global count2 #wanted to eliminate global variable
if(count2>=len(s)):
return no
if(s[count2]=='1'):#count2 is the index of current character in String
no = no+1
count2=count2+1
return no + Ones(s)
else:
count2=count2+1
return Ones(s)
in the above code using count2 as a global variable , is there any possible way to declare and use count2 variable as a local inside the function , have tried like but no luck
def Ones(s):
count2=0 # but everytime it get reset to zero
Note: number of parameter of function should be remain only one and no any other helper function have to use.
The avoidance of explicit state variables is an important part of the recursion concept.
The method you are calling only needs the remainder of the string to find 1s in it. So instead of passing a string, and the position in the string, you can pass only the remainder of the string.
Python's powerful indexing syntax makes this very easy. Just look at it this way: Each instance of the method can take away the part it processed (in this case: one character), passing on the part it didn't process (the rest of the string).
Just like #ypnos said, if you really want to use recursion, here is the code:
def Ones(s):
if not s:
return 0
if s[0]=='1':
return 1 + Ones(s[1:])
else:
return Ones(s[1:])
Hope it helps.

Change Letters to numbers (ints) in python

This might be python 101, but I am having a hard time changing letters into a valid integer.
The put what I am trying to do simply
char >> [ ] >> int
I created a case statement to give me a number depending on certain characters, so what I tried doing was
def char_to_int(sometext):
return {
'Z':1,
'Y':17,
'X':8,
'w':4,
}.get(sometext, '')
Which converts the letter into a number, but when I try using that number into any argument that takes ints it doesn't work.
I've tried
text_number = int(sometext)
But I get the message TypeError: int() argument must be a string or a number, not 'function'
So from there I returned the type of sometext using
print(type(sometext))
And the return type is a function.
So my question is, is there a better way to convert letters into numbers, or a better way to setup my switch/def statement
Heres the full code where its call
if sometext:
for i in range ( 0, len(sometext)):
char_to_int(sometext[i])
I've managed to get it working, ultimately what I changed was the default of the definition, I now set the definition to a variable before instead of calling it in another function, and I recoded the section I was using it.
Originally my definition looked liked this
def char_to_int(sometext):
return {
...
}.get(sometext, '')
But I changed the default to 0, so now it looks like
def char_to_int(sometext):
return {
...
}.get(sometext, 0)
The old code that called the definition looked
if sometext:
for i in range ( 0, len(sometext)):
C_T_I = int(char_to_int(sometext[i]))
I changed it to this.
if sometext:
for i in range ( 0, len(sometext)):
C_T_I = char_to_int(sometext[i])
TEXTNUM = int(C_T_I)
Hopefully this clarifies the changes. Thanks for everyone's assistance.
in the python console:
>>> type({ 'Z':1, 'Y':17, 'X':8, 'w':4, }.get('X', ''))
<class 'int'>
so as cdarke suggested, you should look at how you are calling the function.

Define datatype in Python

I have some inkling of how this might work, but I do not know the exact syntax of how to do it.
An example:
def function(string):
string = string + "A"
How will the function know that what I am inputting is a string?
Is it something along the lines of...
string = type.str
There are some ways to check the type of a variable. First, you could check if the parameter is an instance of str:
def isstring(parameter):
return isinstance(parameter, str)
Another way could be to try to concatenate a string (in this case "") with the parameter and catch eventually exceptions (TypeError exception):
def isstring(parameter):
try:
parameter += ""
return True
except TypeError:
return False
Another way could be to use type (similar to isinstance, but difference mostly when polymorphism is involved):
def isstr(parameter):
return type(parameter) == str
You could also use assert, but if you want just to check if a parameter is of a certain type, I would adopt the first case.
No, you could NOT, python is dynamic but not static, so it could not know the argument type at "compile time", instead, you could check the input type by assert.
def fun(string):
assert isinstance(string, basestring) # we usually check if it type is basestring as this works fine for both ASCII string and Unicode.
string = string + "A"
return string
if __name__ == '__main__':
fun(2)

splitting up strings to x amount of characters

I am trying to make a decrypter that decrypts code from the encrypter I made. I am getting this type error when I run the code though
getcrypt = ''.join(map(Decrypt.get,split_up_into_sixteen_chars(x_str)))
TypeError: split_up_into_sixteen_cjars() takes 0 positional arguments but 1 was given
I'm fairly new to programming and not sure whats causing this.
heres my code
Decrypt = {'1s25FF5ML10IF7aC' : 'A', 1s2afF5ML10I7ac' : 'a'} #I obviously have more than this but I'm trying to make it as simplified as possible
def split_up_into_sixteen_chars():
while len(x_str)>0:
v = x_str[:16]
print(v)
x_str = (input())
getcrypt = ''.join(map(Decrypt.get,split_up_into_sixteen_chars(x_str)))
print(getcrypt)
You have defined a function that takes no parameters:
def split_up_into_sixteen_chars():
yet you are passing it one:
split_up_into_sixteen_chars(x_str)
You need to tell Python that the function takes one parameter here, and name it:
def split_up_into_sixteen_chars(x_str):
The name used does not have to match the name that you pass in for the function call, but it does have to match what you use inside the function. The following function would also work; all I did was rename the parameter:
def split_up_into_sixteen_chars(some_string):
while len(some_string) > 0:
v = some_string[:16]
print(v)
This works because the parameter some_string becomes a local name, local to the function. It only exists inside of the function, and is gone again once the function completes.
Note that your function creates an infinite loop; the length of some_string will either always be 0, or always be longer than 0. The length does not change in the body of the loop.
The following would work better:
def split_up_into_sixteen_chars(some_string):
while len(some_string) > 0:
v = some_string[:16]
print(v)
some_string = some_string[16:]
because then we replace some_string with a shorter version of itself each time.
Your next problem is that the function doesn't return anything; Python then takes a default return value of None. Printing is something else entirely, print() writes the data to your console or IDE, but the caller of the function does not get to read that information.
In this case, you really want a generator function, and use yield. Generator functions return information in chunks; you can ask a generator for the next chunk one by one, and that is exactly what map() would do. Change the function to:
def split_up_into_sixteen_chars(some_string):
while len(some_string) > 0:
v = some_string[:16]
yield v
some_string = some_string[16:]
or even:
def split_up_into_sixteen_chars(some_string):
while some_string:
yield some_string[:16]
some_string = some_string[16:]
because an empty string is 'false-y' when it comes to boolean tests as used by while and if.
As your map(Decrypt.get, ...) stands, if split_up_into_sixteen_chars() yields anything that is not present as a key in Dycrypt, a None is produced (the default value for dict.get() if the key is not there), and ''.join() won't like that. The latter method can only handle strings.
One option would be to return a string default instead:
''.join(map(lambda chunk: Decrypt.get(chunk, ''), split_up_into_sixteen_chars(x_str)))
Now '', the empty string, is returned for chunks that are not present in Decrypt. This makes the whole script work for whatever string input you have:
>>> x_str='Hello world!'
>>> ''.join(map(lambda chunk: Decrypt.get(chunk, ''), split_up_into_sixteen_chars(x_str)))
''
>>> x_str = '1s25FF5ML10IF7aC'
>>> ''.join(map(lambda chunk: Decrypt.get(chunk, ''), split_up_into_sixteen_chars(x_str)))
'A'

Categories

Resources