Printing strings with print() in Python [duplicate] - python

This question already has answers here:
Why is my print function printing the () and the "" along with the statement?
(2 answers)
Closed 5 years ago.
I am learning Python and I run into a syntax problem. When I try to create a function that prints "Hello (name)", the quotation marks and the comma appear alongside the string.
For example:
def sayHello(name = 'John'):
print('Hello ', name)
sayHello()
prints as:
('Hello ', 'John')
Any idea why it's the case?
Thanks!

You code would work as expected in Python 3.
Python 2 uses print statement, i.e command, rather than function.
The command understands your argument as a tuple (pair).
Correct use of print command in Python 2
print 'Hello,' name
Alternatives are
print 'Hello, %s' % name
See Using print() in Python2.x
for details

In python, () means a tuple. It will print "()" if its empty, and "(value1, value2, ...)" if it contains values.
In your example, you print a tuple which contains two values "Hello" and name.
If you want to print "Hello (name)", you could try:
print "Hello ", name
print "Hello " + name

Related

Why is my vowel removal function not working? (Python 2.7) [duplicate]

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 3 years ago.
I'm working through the Python course on codecademy and trying to create a python function that removes vowels in a string and returns the newly modified string.However the function returns the string without any modification (i.e. if I call anti_vowel("abcd") it returns "abcd")
After using a print statement it appears the for loop only runs once, irrespective of the length of the string.
def anti_vowel(string):
for t in string:
if(t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
string.replace(t, " ")
print "test"
print string
return string
Strings in Python are immutable, so you will need to make an assignment back to the original string with the replacement on the RHS:
if (t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
string = string.replace(t, " ")
But, you could also just re.sub here:
string = re.sub(r'[aeiou]+', '', string, flags=re.IGNORECASE)
You have the return statement inside the for a loop that is why your code is your loop is executing exactly once. Place it outside the loop and your code will work fine.
def anti_vowel(string):
for t in string:
if(t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
string.replace(t, " ")
print "test"
print string
return string
For replacing the vowel characters, you cannot replace in the existing variable as strings in python are immutable. You can try this
def anti_vowel(string):
for t in string:
if(t.lower()=='a' or t.lower()=='e' or t.lower()=='i' or t.lower()=='u'):
string=string.replace(t, " ")
print "test"
print string
return string

Why can .format() not be used separately from the declaration? [duplicate]

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 4 years ago.
Can someone explain to me what is going on with the .format() method that it only works off a string declaration and not on a variable containing a string?
Below are the example of the working and failing code followed by the output of each
# This works fine
s = "{0} \n" \
"{1} \n" \
"{2}\n" \
.format("Hello", "world", "from a multiline string")
print(s)
# This does not
f = "{0} \n" \
"{1} \n" \
"{2}\n"
f.format("Hello", "world", "from a multiline string")
print(f)
respective output
Hello
world
from a multiline string
{0}
{1}
{2}
I have tried this with no numbers in braces({}) as well as by assigning names ({aname}) and passing keyword arguments. I'd like to understand the difference between the first and second examples in how the format method processes them, and if there is a way to format a variable containing a string separate from the actual declaration.
It is working, but you will need to reassign it back since it is not in-place (= it creates a new string object, just like any other str method).
f = "{0} \n" \
"{1} \n" \
"{2}\n"
f = f.format("Hello", "world", "from a multiline string")
print(f)
# Hello
# world
# from a multiline string
because .format function returns the formatted string.
It doesn't format the string on which it's called, but it will return you a new string object having the formatted result.

Python : Input, Raw input error [duplicate]

This question already has answers here:
"NameError: name '' is not defined" after user input in Python [duplicate]
(3 answers)
Closed 6 years ago.
I am trying a simple Hello world, this is my code-
def hello(name=''):
if len(name) == 0 :
return "Hello, World!"
else :
return "Hello, %s!" %(name)
my_name = raw_input()
x = hello(my_name)
print (x)
This code works fine if I use raw_input, but if I use input, it gives an error.
Doesn't the new python not support raw_input.
I also want to know why I defined the parameter in my function as following-
def hello(name='')
Why did I need to use the '' after name
I am really confused, please help. If you have any advice to improve my program, it's appreciated
If you are passing string with input, you have to also mention the double quotes ", for example "My Name"
Whereas in raw_input, all the entered values are treated as string by default
Explanation:
# Example of "input()"
>>> my_name = input("Enter Name: ")
Enter Name: "My Name"
# Passing `"` with the input, else it will raise NameError Exception
>>> my_name
'My Name' <--- value is string
# Example of "raw_input()"
>>> my_name = raw_input("Enter Name: ")
Enter Name: My Name
# Not passing any `"`
>>> my_name
'My name' <--- still value is string

Replace not working in python [duplicate]

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 7 years ago.
While trying basic python scripting in eclipse IDE, I am encountering problem:
I just tried a simple code, which I found online:
var = 'hello , world'
print "%s" % var
var.strip(',')
print "%s" % var
The result i am getting is
hello , world
hello , world
Also i tried with replace command, but the result remain unchanged
var = 'hello , world'
print "%s" % var
var.replace(',', '')
print "%s" % var
The result obtained is
hello , world
hello , world
I could not figure out were I am making mistake.
In Python, strings are immutable, change:
var.replace(',', '')
to
var = var.replace(',', '')
Strings in Python are immutable. That means any methods that operate on them don't change the value, they return a new value.
What you need is
var = 'hello , world'
print "%s" % var
var = var.replace(',') # Replace the variable.
print "%s" % var
Also, print "%s" % var is redundant. You can just use print var.

Invalid syntax when using "print"? [duplicate]

This question already has answers here:
Syntax error on print with Python 3 [duplicate]
(3 answers)
Closed 9 years ago.
I'm learning Python and can't even write the first example:
print 2 ** 100
this gives SyntaxError: invalid syntax
pointing at the 2.
Why is this? I'm using version 3.1
That is because in Python 3, they have replaced the print statement with the print function.
The syntax is now more or less the same as before, but it requires parens:
From the "what's new in python 3" docs:
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Old: print # Prints a newline
New: print() # You must call the function!
Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)
Old: print (x, y) # prints repr((x, y))
New: print((x, y)) # Not the same as print(x, y)!
You need parentheses:
print(2**100)
They changed print in Python 3. In 2 it was a statement, now it is a function and requires parenthesis.
Here's the docs from Python 3.0.
The syntax is changed in new 3.x releases rather than old 2.x releases:
for example in python 2.x you can write:
print "Hi new world"
but in the new 3.x release you need to use the new syntax and write it like this:
print("Hi new world")
check the documentation:
http://docs.python.org/3.3/library/functions.html?highlight=print#print

Categories

Resources