Python: can a function return a string? - python

I am making a recursive function that slices string until it is empty. When it is empty it alternatively selects the characters and is supposed to print or return the value. In this case I am expecting my function to return two words 'Hello' and 'World'. Maybe I have got it all wrong but what I don't understand is that my function doesn't let me print or return string. I am not asking for help but I'd like some explanation :) thanks
def lsubstr(x):
a= ''
b= ''
if x == '':
return ''
else:
a = a + x[0:]
b = b + x[1:]
lsubstr(x[2:])
#print (a,b)
return a and b
lsubstr('hweolrllod')
so I changed my code to this:
def lsubstr(x):
if len(x) <1:
return x
else:
return (lsubstr(x[2:])+str(x[0]),lsubstr(x[2:])+str(x[1]))
lsubstr('hweolrllod')
and what I am trying to make is a tuple which will store 2 pairs of characters and concatenate the next ones,
the error I get is
TypeError: Can't convert 'tuple' object to str implicitly
what exactly is going wrong, I have checked in visualization, it has trouble in concatenating.

The and keyword is a boolean operator, which means it compares two values, and returns one of the values. I think you want to return a tuple instead, like this:
...
return (a, b)
And then you can access the values using the indexing operator like this:
a = lsubstr( ... )
a[0]
a[1]
Or:
word1, word2 = lsubstr( ... )

Related

How to add multiple print functions into one string

I have multiple function that instead of returning they print a certain string I can’t put the whole function but that’s what they end up doing I want to take all of these function and make them into a single string.
Here’s an example of what one function would print and what I tried
def print_names(lst):
print(name)
def print_id(lst):
print(id)
lst = [name, not_name, not_name,id]
print_id(lst) + print_name(lst)
Doing this I get the error unsupported operand types for +: none type
You are getting this error because you are trying to add together the returned value for your print_names and print_id methods.
Since there is no return statement in these methods, the return value will be None and you cannot apply the + operator to the none type.
If you want to print these two items in your list together as one string, you would need to return the items, add them together, and print that:
lst = ['name', 'not_name', 'not_name','id']
def get_name(lst):
return lst[0]
def get_id(lst):
return lst[3]
print get_id(lst) + get_name(lst)
ok you should do it like this
def print_names(lst):
return lst[0]
def print_id(lst):
return lst[3]
lst = [name, not_name, not_name,id]
id_and_name = print_names(lst) + print_id(lst)
after that you will be able to print the "id_and_name" together
If you tried to return the Values, it would make it easier
def print_names(lst):
#rest of the function
return name
def print_id(lst):
#rest of the function
return id
lst = [name, not_name, not_name,id]
print(print_id(lst) + print_names(lst))
Functions return None, unless stated otherwise. print_id and print_name are returning both returning None and you are trying to add None + None which is not possible.
You can just return strings, concatenate (join) the two strings, and print that new string:
def get_name(lst):
return str(lst[0])
def get_id(lst):
return str(lst[3])
print(get_name(lst) + " " + get_id(lst))
or f-strings:
print(f"{get_name(lst)} {get_id(lst)}")
Or, use a dictionary so you dont need to index the data:
user_data = {
"name": "tom"
"id": 123456
}
print(f"{user_data["name"]} {user_data["id"]}")

python, printing longest length of string in a list

My question is to write a function which returns the longest string and ignores any non-strings, and if there are no strings in the input list, then it should return None.
my answer:
def longest_string(x):
for i in max(x, key=len):
if not type(i)==str:
continue
if
return max
longest_string(['cat', 'dog', 'horse'])
I'm a beginner so I have no idea where to start. Apologies if this is quite simple.
This is how i would do it:
def longest_string(x):
Strings = [i for i in x if isinstance(i, str)]
return(max(Strings, key=len)) if Strings else None
Based on your code:
def longest_string(x):
l = 0
r = None
for s in x:
if isinstance(s, str) and len(s) > l:
l = len(s)
r = s
return r
print(longest_string([None, 'cat', 1, 'dog', 'horse']))
# horse
def longest_string(items):
try:
return max([x for x in items if isinstance(x, str)], key=len)
except ValueError:
return None
def longest_string(items):
strings = (s for s in items if isinstance(s, str))
longest = max(strings, key=len) if strings else None
return longest
print(longest_string(['cat', 'dog', 'horse']))
Your syntax is wrong (second-to-last line: if with no condition) and you are returning max which you did not define manually. In actuality, max is a built-in Python function which you called a few lines above.
In addition, you are not looping through all strings, you are looping through the longest string. Your code should instead be
def longest_string(l):
strings = [item for item in l if type(item) == str]
if len(strings):
return max(strings, key=len)
return None
You're on a good way, you could iterate the list and check each item is the longest:
def longest_string(x)
# handle case of 0 strings
if len(x) == 0:
return None
current_longest = ""
# Iterate the strings
for i in x:
# Handle nonestring
if type(i) != str:
continue
# if the current string is longer than the longest, replace the string.
if len(i) > len(current_longest):
current_longest = i
# This condition handles multiple elements where none are strings and should return None.
if len(current_longest) > 0:
return current_longest
else:
return None
Since you are a beginner, I recommend you to start using python's built-in methods to sort and manage lists. Is the best when it comes to logic and leaves less room for bugs.
def longest_string(x):
x = filter(lambda obj: isinstance(obj, str), x)
longest = max(list(x), key=lambda obj: len(obj), default=None)
return longest
Nonetheless, you were in a good way. Just avoid using python´s keywords for variable names (such as max, type, list, etc.)
EDIT: I see a lot of answers using one-liner conditionals, list comprehension, etc. I think those are fantastic solutions, but for the level of programming the OP is at, my answer attempts to document each step of the process and be as readable as possible.
First of all, I would highly suggest defining the type of the x argument in your function.
For example; since I see you are passing a list, you can define the type like so:
def longest_string(x: list):
....
This not only makes it more readable for potential collaborators but helps enormously when creating docstrings and/or combined with using an IDE that shows type hints when writing functions.
Next, I highly suggest you break down your "specs" into some pseudocode, which is enormously helpful for taking things one step at a time:
returns the longest string
ignores any non-strings
if there are no strings in the input list, then it should return None.
So to elaborate on those "specifications" further, we can write:
Return the longest string from a list.
Ignore any element from the input arg x that is not of type str
if no string is present in the list, return None
From here we can proceed to writing the function.
def longest_string(x: list):
# Immediately verify the input is the expected type. if not, return None (or raise Exception)
if type(x) != list:
return None # input should always be a list
# create an empty list to add all strings to
str_list = []
# Loop through list
for element in x:
# check type. if not string, continue
if type(element) != str:
pass
# at this point in our loop the element has passed our type check, and is a string.
# add the element to our str_list
str_list.append(element)
# we should now have a list of strings
# however we should handle an edge case where a list is passed to the function that contains no strings at all, which would mean we now have an empty str_list. let's check that
if not str_list: # an empty list evaluates to False. if not str_list is basically saying "if str_list is empty"
return None
# if the program has not hit one of the return statements yet, we should now have a list of strings (or at least 1 string). you can check with a simple print statement (eg. print(str_list), print(len(str_list)) )
# now we can check for the longest string
# we can use the max() function for this operation
longest_string = max(str_list, key=len)
# return the longest string!
return longest_string

return value from a string in list python

I have test = ['1234'] and I need to return only '1'
How should I get it?
I have been trying s.find('1') but this gets me the index of 1, its not that I want.
I can use print( "First character in string : " , string[0] ) but again it works with an index.
I tried this:
test = ['1234']
test[0][0]
but it works only if I know that 1 is first element of my string. What should I do if I didn't know this?
You can use find to find the index of your string and find the element stored at that index. However, it doesn't make sense to me as you already have the element you want to find. I am assuming you have posted your true purpose.
Try this:
li = ['12345']
def foo():
return li[0][li[0].find('1')]
print("Answer:", foo())
Outputs:
Answer: 1
s = '12345'
def foo():
return s[0]
foo()

How to XOR two strings in Python

H, I'm trying to XOR two strings (which should become hex first) in Python.
I know one way will work:
def xor_two_str(str1, str2):
return hex(int(str1,16) ^ int(str2,16))
But I tried sth like this:
def change_to_be_hex(str):
return hex(int(str,base=16))
def xor_two_str(str1,str2):
a = change_to_be_hex(str1)
b = change_to_be_hex(str2)
return hex(a ^ b)
print xor_two_str("12ef","abcd")
This will return TypeError: ^ shouldn't be used between str, str.
I don't know why.
And also this function won't work:
bcd = change_to_be_hex("12ef")
def increment_hex(hex_n):
return hex_n + 1
result = increment_hex(bcd)
print result
The error message is : TypeError: cannot concatenate 'str' and 'int' objects
I feel this is so strange:(
Thank you!
Hi,
The following function is returning the result of hex() which returns a string.
def change_to_be_hex(s):
return hex(int(s,base=16))
You should use the ^ operator on integers.
def change_to_be_hex(s):
return int(s,base=16)
def xor_two_str(str1,str2):
a = change_to_be_hex(str1)
b = change_to_be_hex(str2)
return hex(a ^ b)
print xor_two_str("12ef","abcd")
I'm not sure though that's the result you're looking for. If you want to XOR two strings, it means you want to XOR each character of one string with the character of the other string. You should then XOR ord() value of each char or str1 with ord() value of each char of str2.
def xor_two_str(a,b):
xored = []
for i in range(max(len(a), len(b))):
xored_value = ord(a[i%len(a)]) ^ ord(b[i%len(b)])
xored.append(hex(xored_value)[2:])
return ''.join(xored)
print xor_two_str("12ef","abcd")
Or in one line :
def xor_two_str(a,b):
return ''.join([hex(ord(a[i%len(a)]) ^ ord(b[i%(len(b))]))[2:] for i in range(max(len(a), len(b)))])
print xor_two_str("12ef","abcd")
hex returns a string, so you're trying to xor two strings.
def change_to_be_hex(s):
return int(s,base=16)
Should fix this.
when you initially return hex, like in change_to_be_hex, you explicitly convert it to int. you need to do that throughout your code to add something to it - so, change increment_hex to:
return (int(hex_n) + 1)

list to integer

I'm trying to write a recursive python function that takes in a list for example [1,2,3,4] and returns an integer 1234. Any help on how to do this
def listtoint(lst):
if lst==[]:
return 0
return lst[-1:]+clti(lst/10)
I know you can't divide the list but I would like a way to get around it
def listtoint(lst):
if lst == []:
return 0
s = ''.join([str(i) for i in lst])
return int(s)
How this works is: ''.join(some_list) takes every element of the list and concatenates them into one long string. every element of some_list here must already be a string, thus the list comprehension in the code above.
int is then used to turn the resulting string into an integer.
There should be error checking but you can deal with that. Also, this isn't recursive and doesn't need to be.
To do this recursively...
def listtoint(lst):
if lst==[]:
return 0
iPower = 10**(len(lst)-1)
return lst[0]*iPower + listtoint(lst[1:])

Categories