How to add multiple print functions into one string - python

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"]}")

Related

Break a string and reverse each element of it

I'm learning data and algorithm, here is the question I met
Question:Write a short recursive Python function that takes a character string s and
outputs its reverse. For example, the reverse of pots&pans would be
snap&stop .
a="pots&pans"
b=a.split("&")
c=[]
c=list(b)
def reverse(data,leng,leng2,index,count):
rev=(leng-1)-count
if count<leng/2:
temp=data[index][count]
data[index][count]=data[index][rev]
data[index][rev]=temp
if index==leng2:
print(data[index-1]+"&"+data[index])
return reverse(data,leng,leng2,index+1,count)
reverse(c,4,2,0,0)
I got an error here
TypeError: 'str' object does not support item assignment
My initial thought is that str is immutable. So it is better to store it in an list and do the operations. However, it met some problem when I trying to assign str to a list. Any solution to this?
Try this:
a="pots&pans"
b=a.split("&")
def reverse(word):
if not word:
return ""
return reverse(word[1:]) + word[0]
result = reverse(b[1]) + "&" + reverse(b[0])
print(result)
If you want one recursion to also reverse all the words position:
a="pots&pans&hello&hi"
b=a.split("&")
def reverse(lis):
if not lis:
return ""
if type(lis) == list and len(lis) == 1:
return reverse(lis[0])
if type(lis) == str:
return reverse(lis[1:]) + lis[0]
if type(lis) == list:
return reverse(lis[1:]) + "&" + reverse(lis[0])
print(reverse(b))
One recursive approach would be to append the first character to the reverse of the rest of the string:
def rev(s): return rev(s[1:])+s[0] if s else ""
output:
rev("pots&pans")
'snap&stop'
You could also do this without indexing using parameter unpacking:
def rev(first,*rest): return rev(*rest)+first if rest else first
rev(*"pots&pans")
'snap&stop'
Try this:
a="pots&pans"
def reverse(a_string):
`letter_list = list(a_string)`
`letter_list.reverse()`
`return(''.join(letter_list))`
print(reverse(a))

alternative for range and len functions

In the For loop below
def __str__(self):
output = " "
for i in range(len(self)):
output += (self.str_data[i] +" ")
return output
How may I rewrite this without using range & len or any other inbuilt function?
PS: str_data was used as instance variable of type list in init earlier.
If you're allowed to use join() then you could do:
def __str__(self):
return " ".join(self.str_data)
This is of course assuming len(self) would result in the same as len(self.str_data).
To result in exactly the same as your loop it would actually have to be:
def __str__(self):
if self.str_data:
return " " + " ".join(self.str_data) + " "
else:
return " "
New Answer: (no builtin functions)
def __str__(self):
output=""
for i in self.str_data:
output+=i+" "
return output
Old Answer :
asterisk and double asterisk can be used within list, tuple, set and dictionary, * will unpack list/tuple and ** will unpack dictionary.
my_array = [0,1,2,3,4,5]
print(*my_array) # unpacking list
Another method using join:
print(' '.join(map(str,my_array)))
Output
0 1 2 3 4 5
For the given question:
Since return keyword returns only one argument we can't unpack the list and we have to use function
def __str__(self):
return ' '.join(self.str_data)
You mean like this ?
class A(object):
def __init__(self, str_data):
self.str_data = str_data
def __str__(self):
return " ".join(str(s) for s in self)
def __iter__(self):
return iter(self.str_data)
if __name__ == '__main__':
print(A(["1", "2", "3", "4", "5"]))
import json
def __str__(self):
output = json.dumps(self.str_data)
output = output[1:-1].replace(',', ' ')
return output
For your consideration.
The previous answer is perfectly fine (if you omit builtins), but here's a closer version to what you did:
output = ""
array = [0,1,2,3,4,5]
for i in array:
output += "%s " % (i)
output = output[:-1]
return output
Please note that I change the way you set your output, as I think in order to get the result you want. Like you asked it does not use any builtin and it works just fine.
You could use highlevel functions like
" ".join(map(lambda x:x+" ",self.str_data))
map applies the function to add a space to each string in self.str_data and " ".join adds each of those to the starting string.
But of course these are built-in functions, it's just a really clean solution.
Alternitive to len() could be for loop - like:
var1 = 0
for var2 in list1:
var1 += 1

Python: can a function return a string?

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( ... )

How do I join a list and then delete the last character?

I'm trying to write a function that joins a list of elements and then returns that join without the last character.
This is what I have so far:
n = ["Andy", "Warhol"]
def littery(word):
total = ''
for i in range(len(word)):
total = total + word[i]
return total
littery(n)
a = littery(n)[0:len(littery(n))-1]
print
The program prints: AndyWarho
Is there a better way to do this? I want to do this inside the function, without using: a = littery(n)[0:len(littery(n))-1]
If I understand what you're trying to do correctly, you can just do this:
def littery(lst):
return ''.join(lst)[:-1]
>>> littery(['Andy', 'Warhol'])
'AndyWarho'
Or if you want to take the last element off of each element of lst, you could do this:
def littery(lst):
return ''.join(word[:-1] for word in lst)
>>> littery(['Andy', 'Warhol'])
'AndWarho'
Or if you don't want to build a list in the call, you can do this:
def littery(*lst):
return ''.join(lst)[:-1]
>>> littery('Andy', 'Warhol')
'AndyWarho'
Or if you want to do it another way, you can do this:
def littery(*lst):
return ''.join(lst[:-1] + [lst[-1][:-1]])
Or if you might need the slice again at some point:
last = slice(-1)
def littery(*lst):
return ''.join(lst)[last]

Why does list.append() return None? [duplicate]

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 2 years ago.
I am trying to calculate a postfix expression using Python, but it did not work. I think this is maybe a Python-related problem.
Any suggestions?
expression = [12, 23, 3, '*', '+', 4, '-', 86, 2, '/', '+']
def add(a,b):
return a + b
def multi(a,b):
return a* b
def sub(a,b):
return a - b
def div(a,b):
return a/ b
def calc(opt,x,y):
calculation = {'+':lambda:add(x,y),
'*':lambda:multi(x,y),
'-':lambda:sub(x,y),
'/':lambda:div(x,y)}
return calculation[opt]()
def eval_postfix(expression):
a_list = []
for one in expression:
if type(one)==int:
a_list.append(one)
else:
y=a_list.pop()
x= a_list.pop()
r = calc(one,x,y)
a_list = a_list.append(r)
return content
print eval_postfix(expression)
Just replace a_list = a_list.append(r) with a_list.append(r).
Most functions, methods that change the items of sequence/mapping does return None: list.sort, list.append, dict.clear ...
Not directly related, but see Why doesn’t list.sort() return the sorted list?.
The method append does not return anything:
>>> l=[]
>>> print l.append(2)
None
You must not write:
l = l.append(2)
But simply:
l.append(2)
In your example, replace:
a_list = a_list.append(r)
to
a_list.append(r)
For return data on append use:
b = []
a = b.__add__(['your_data_here'])
append function mutates the list and it returns None. This is the piece of code which does that http://hg.python.org/cpython/file/aa3a7d5e0478/Objects/listobject.c#l791
listappend(PyListObject *self, PyObject *v)
{
if (app1(self, v) == 0)
Py_RETURN_NONE;
return NULL;
}
So, when you say
a_list = a_list.append(r)
you are actually assigning a_list with None. So, the next time when you refer to a_list, it is not pointing to the list but the None. So, as others have suggested, change
a_list = a_list.append(r)
to
a_list.append(r)
Functions like list.append(),list.sort() don't return anything.
e.g
def list_append(p):
p+=[4]
function list_append doesn't have an return statement.so when you run following statements:
a=[1,2,3]
a=list_append(a)
print a
>>>None
but when you run following statements:
a=[1,2,3]
list_append(a)
print a
>>>[1,2,3,4]
That's it.so,hoping it can help you.
List methods can be divided in two types those who mutate the lists in place and return None (literally) and those who leave lists intact and return some value related to the list.
First category:
append
extend
insert
remove
sort
reverse
Second category:
count
index
The following example explains the differences.
lstb=list('Albert')
lstc=list('Einstein')
lstd=lstb+lstc
lstb.extend(lstc)
# Now lstd and lstb are same
print(lstd)
print(lstb)
lstd.insert(6,'|')
# These list-methods modify the lists in place. But the returned
# value is None if successful except for methods like count, pop.
print(lstd)
lstd.remove('|')
print(lstd)
# The following return the None value
lstf=lstd.insert(6,'|')
# Here lstf is not a list.
# Such assignment is incorrect in practice.
# Instead use lstd itself which is what you want.
print(lstf)
lstb.reverse()
print(lstb)
lstb.sort()
print(lstb)
c=lstb.count('n')
print(c)
i=lstb.index('r')
print(i)
pop method does both. It mutates the list as well as return a value.
popped_up=lstc.pop()
print(popped_up)
print(lstc)
just a thought, instead of those functions (which manipulates the actual data) returning None, they should have returned nothing.
Then atleast the user would have caught the issue as it would have throwed an error stating some assignment error!!
Comment your thoughts!!
Just in case somebody ends here, I encountered this behavior while trying to append on a return call
This works as expected
def fun():
li = list(np.random.randint(0,101,4))
li.append("string")
return li
This returns None
def fun():
li = list(np.random.randint(0,101,4))
return li.append("string")

Categories