Python pass print statement including non strings to function - python

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)

Related

String manipulation using list comprehension

I am trying below code and expecting output as,
matching string where every even letter is uppercase, and every odd letter is lowercase, however my output is list of all uppercase characters.
def myfunc(*args):
return ''.join([args[i].upper() if i%2==0 else args[i].lower() for i in range(len(args))])
How can I get expected output ? I tried same list comprehension syntax to test and it works fine. What's wrong with this specific code ?
By writing *args in your function declaration, it means that you're iterating over a number of strings and not just one string. For example:
myfunc('hello', 'goodbye')
Your function will iterate over a hello and goodbye, with hello having an index of 0 which is even number and thus converting its characters to uppercase, whereas goodbye has an index of 1 which is odd and thus covnerting its characters to lowercase:
HELLOgoodbye
If you wish to call your function for only one string, you have to remove the * from *args or inserting the string's characters one by one:
myfunc('h','e','l','l','o')
So, the declaration and implementation of your function should look like this:
def myfunc(args):
return ''.join([args[i].upper() if i%2==0 else args[i].lower() for i in range(len(args))])
Calling myfunc('hello') will return the correct result.
The problem is, you're using var-args. That's wrapping the string passed with a list, then you're iterating over that list (which only contains one string). This means your code does work to some extent; its just alternating the case of each whole word instead of each character.
Just get rid of the var-args:
def myfunc(word):
return ''.join([word[i].upper() if i%2==0 else word[i].lower() for i in range(len(word))])
print(myfunc("hello world"))
# HeLlo WoRlD
I'll just note, there's a few ways this could have been debugged. If you had checked the contents of args, you would have seen that it only contained a single element when one argument was passed, and two when two arguments were passed. If you had passed two arguments in, you would have also noticed that it alternated the case of each word as a whole. That would have likely given you enough hints to figure it out.
The above answers are correct but they ask you to modify the current syntax. In general you should try to understand how *args works.
In python, *args in a function definition is used to receive variable number of arguments. Such cases arise when we don't know in advance how many arguments will be passed.
For example :
def myFun(*argv):
for arg in argv:
print (arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
Now coming back to your code, you can make it run by selecting the first argument from the args list. See below :
def myfunc(*args):
return ''.join([args[0][i].upper() if i%2==0 else args[0][i].lower() for i in range(len(args[0]))])
print(myfunc("input"))
Help the community by selecting the best answer for this question.

Not getting the desired output in python

enter image description hereI want to reverse a number. If 92 is typed the result should be 29. The code is given below
def intreverse(n) :
a=str(n)
b=a[::-1]
c=int(b)
print (c)
But i am getting the result as actual output as
29/n
none/n
Why?
The course you use probably wants you to write functions with returns. As your function has no return, you get None in the end. And for the newline character \n: As you print your answer, print puts a newline character after what you print. If you delete the print statement and put a return statement instead as suggested, both problems will be solved.
It looks like you are getting newlines in your text input (possibly two?). I would fix this with
a=str(n).strip()
also, you are printing the result, I think you want to return it. Since the function does not return anything, a = intreverse('29') will assign None to a. So you want:
def intreverse(n) :
a=str(n).strip()
b=a[::-1]
c=int(b)
return c
Or just for the obligatory one-liner:
def intreverse(n):
return int(str(n).strip()[::-1])

Strange behaviour with String reversal function

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'

Difference between using commas, concatenation, and string formatters in Python

I am learning python(2.7) on my own.
I have learned that we can use the following ways to put strings and variables together in printing:
x = "Hello"
y = "World"
By using commas:
print "I am printing" , x, y # I know that using comma gives automatic space
By using concatenation :
print "I am printing" + " " + x + " " + y
By using string formatters
print "I am printing %s %s" % (x, y)
In this case all three print the same:
I am printing Hello World
What is the difference between the three and are there any particular instances where one is preferred over the other?
To answer the general question first, you would use printing in general to output information in your scripts to the screen when you're writing code to ensure that you're getting what you expect.
As your code becomes more sophisticated, you may find that logging would be better than printing, but that's information for another answer.
There is a big difference between printing and the return values' representations that are echoed in an interactive session with the Python interpreter. Printing should print to your standard output. The echoed representation of the expression's return value (that show up in your Python shell if not None) will be silent when running the equivalent code in scripts.
1. Printing
In Python 2, we had print statements. In Python 3, we get a print function, which we can also use in Python 2.
Print Statements with Commas (Python 2)
The print statement with commas separating items, uses a space to separate them. A trailing comma will cause another space to be appended. No trailing comma will append a newline character to be appended to your printed item.
You could put each item on a separate print statement and use a comma after each and they would print the same, on the same line.
For example (this would only work in a script, in an interactive shell, you'd get a new prompt after every line):
x = "Hello"
y = "World"
print "I am printing",
print x,
print y
Would output:
I am printing Hello World
Print Function
With the built-in print function from Python 3, also available in Python 2.6 and 2.7 with this import:
from __future__ import print_function
you can declare a separator and an end, which gives us a lot more flexibility:
>>> print('hello', 'world', sep='-', end='\n****\n')
hello-world
****
>>>
The defaults are ' ' for sep and '\n' for end:
>>> print('hello', 'world')
hello world
>>>
2. String Concatenation
Concatenation creates each string in memory, and then combines them together at their ends in a new string (so this may not be very memory friendly), and then prints them to your output at the same time. This is good when you need to join strings, likely constructed elsewhere, together.
print('hello' + '-' + 'world')
will print
hello-world
Be careful before you attempt to join in this manner literals of other types to strings, to convert the literals to strings first.
print('here is a number: ' + str(2))
prints
here is a number: 2
If you attempt to concatenate the integer without coercing it to a string first:
>>> print('here is a number: ' + 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
This should demonstrate that you should only ever attempt to concatenate variables that are known to be strings. The new way of formatting demonstrated next handles this issue for you.
3. String Interpolation
The formatting you're demonstrating is the old style of string interpolation, borrowed from C. It takes the old string and one time creates a new one. What it does is fairly straightforward. You should use this when you may seem likely to building up a fairly large template (at 3+ lines and 3+ variables, you definitely should be doing it this way).
The new way of doing that would be to do this (using the index of the arguments):
print('I am printing {0} and {1}'.format(x, y))
or in python 2.7 or 3 (using the implied index):
print('I am printing {} and {}'.format(x, y))
or with named arguments (this is semantically easy to read, but the code doesn't look very DRY (i.e. Don't Repeat Yourself))
print('I am printing {x} and {y}'.format(x=x, y=y))
The biggest benefit of this over % style formatting (not demonstrated here) is that it lets you combine positional and keyword arguments
print('I am printing {0} and {y}'.format(x, y=y))
New in Python 3.6, format literals
Python 3.6 will have format literals, with a more elegant syntax (less redundancy). The simple syntax is something like:
print(f'I am printing {x} and {y}')
The format literals can actually execute code in-place:
>>> print(f'I am printing {"hello".capitalize()} and {"Wo" + "rld"}')
I am printing Hello and World
you should build list and use join with delimiter
for example
",".join(list_name)

String Delimiter in Python

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

Categories

Resources