I am using recursion to reverse a string. I am able to reverse a string successfully using following code.
def rev(string):
if len(string)==0:
return string
if len(string)==1:
return string
else:
s=string
string = s[-1]+rev(s[:-1])
return string
But when i am replacing return with print it is printing only the first two characters of answer and then throwing an error saying
"TypeError: cannot concatenate 'str' and 'NoneType' objects"
Example. when give 'StackOverflow' to function and returned a value it returns 'wolfrevOkcatS' corrrectly
but when I am trying to print the answer in the function itself, it is only printing "tS" giving the error above.
I suspect that you did something like this:
def rev(string):
if len(string)==0:
print string
if len(string)==1:
print string
else:
s=string
string = s[-1]+rev(s[:-1])
print string
Let's get right to the problem. Supposed the string you are trying to reverse is abc. In the first call, you will hit the else clause and try to evaluate:
'c' + rev('ab')
The problem is now that your function has no return statements, rev('ab') returns None. And python raises an error when you try to concatenate a string with None.
With the return statements. rev('ab') returns 'ba' and the plus sign can be used to concatenate 'c' with 'ba'.
As an aside, if you are ever trying to solve this problem in production code, you should be using the built in tools.
reversed_str = myStr[::-1]
reversed_str_iterator = reversed(myStr)
If you're replacing return with print, your function will not return anything. In Python, that is the same as returning None. This breaks your recursive step where you concatenate the last letter of the string with the return value of the recursive call. Instead, you should just let the recursive call do its own printing (just call it), after print the last letter in a separate statement:
else:
print(s[-1], end="") # or print s[-1], (with the comma!) if you're on Python 2
rev(s[:-1])
Note that you probably want your base cases to print a newline in this situation, since otherwise you won't get one at all.
If you don't return from a function, then the function implicitly returns None. By replacing return with print, you break the recursive functionality; it recurses, but the values computed in the recursive calls are not returned and used. If you want to print intermediate results for your own edification, do so, but do so just before each return statement, not in place of the return statements.
To reverse a string/list in Python use list[::-1]
Demo
>>> my_str = 'StackOverflow'
>>> my_str[::-1]
'wolfrevOkcatS'
I'm trying to generate a log class which has a function that takes input and prints it to a log file. When printing to the console an example can be:
print("hi",[1,2,3])
which results in
hi [1,2,3]
However I have a function:
def printLog(input):
self.file.write('%s\n' % input)
However, passing this combination wouldn't work right. Is there someway I can pass "hi, [1,2,3]" as a string. This would have to convert the list to be printed exactly as it is printed in the console screen? This should deal with all data types, not just lists.
Use the file argument of print() function:
def printLog(*inp):
print(*inp, file=self.file)
You need to build the string yourself. The print statement (and function, when available) automatically calls str on each of its arguments, then prints them separated (by default) by a space.
def printLog(*input):
self.file.write('%s\n' % (" ".join(str(x) for x in input),))
how bout
print("A",[1,2,3],file=self.file)
Well, if I'm not mistaken, couldn't you just typecast the input into a string using str() right after you define printLog?
def printLog(input):
input = str(input)
self.file.write('%s\n' % input)
I want to do split a string using "},{" as the delimiter. I have tried various things but none of them work.
string="2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3 "
Split it into something like this:
2,1,6,4,5,1
8,1,4,9,6,6,7,0
6,1,2,3,9
2,3,5,4,3
string.split("},{") works at the Python console but if I write a Python script in which do this operation it does not work.
You need to assign the result of string.split("},{") to a new string. For example:
string2 = string.split("},{")
I think that is the reason you think it works at the console but not in scripts. In the console it just prints out the return value, but in the script you want to make sure you use the returned value.
You need to return the string back to the caller. Assigning to the string parameter doesn't change the caller's variable, so those changes are lost.
def convert2list(string):
string = string.strip()
string = string[2:len(string)-2].split("},{")
# Return to caller.
return string
# Grab return value.
converted = convert2list("{1,2},{3,4}")
You could do it in steps:
Split at commas to get "{...}" strings.
Remove leading and trailing curly braces.
It might not be the most Pythonic or efficient, but it's general and doable.
I was taking the input from the console in the form of arguments to the script....
So when I was taking the input as {{2,4,5},{1,9,4,8,6,6,7},{1,2,3},{2,3}} it was not coming properly in the arg[1] .. so the split was basically splitting on an empty string ...
If I run the below code from a script file (in Python 2.7):
string="2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3 "
print string.split("},{")
Then the output I got is:
['2,1,6,4,5,1', '8,1,4,9,6,6,7,0', '6,1,2,3,9', '2,3,5,4,3 ']
And the below code also works fine:
string="2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3 "
def convert2list(string):
string=string.strip()
string=string[:len(string)].split("},{")
print string
convert2list(string)
Use This:
This will split the string considering },{ as a delimiter and print the list with line breaks.
string = "2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3"
for each in string.split('},{'):
print each
Output:
2,1,6,4,5,1
8,1,4,9,6,6,7,0
6,1,2,3,9
2,3,5,4,3
If you want to print the split items in the list only you can use this simple print option.
string = "2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3"
print string.split('},{')
Output:
['2,1,6,4,5,1', '8,1,4,9,6,6,7,0', '6,1,2,3,9', '2,3,5,4,3']
Quite simply ,you have to use split() method ,and "},{" as a delimeter, then print according to arguments (because string will be a list ) ,
like the following :
string.split("},{")
for i in range(0,len(string)):
print(string[i])