Replace not working in python [duplicate] - python

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.

Related

Print more than one value [duplicate]

This question already has answers here:
How can I print multiple things (fixed text and/or variable values) on the same line, all at once?
(13 answers)
Printing variables in Python 3.4
(6 answers)
How can I print variable and string on same line in Python? [duplicate]
(18 answers)
How to print formatted string in Python3?
(6 answers)
Closed 2 years ago.
C++
std::cout << "Hello world!";
// output: Hello world!
Python
print("Hello world!")
# output: Hello world!
That works. But how can I do this in Python?
std::string name = "Robert";
std::cout << "Hello " << name << ", how are you?";
Just use commas to seperate arguments:
print("Hello ", name, ", how are you?", sep='')
You can also use the f string formatter:
print(f"Hello {name}, how are you?")
or also with str.format():
print("Hello {}, how are you?".format(name))
You can try this:-
name = 'Robert'
print(f'Hello {name}, how are you?')
OR
print('Hello ', name, ', how are you?', sep='')
Output:-
Hello Robert, how are you?
name = 'Robert'
print('Hello ', name,', how are you?',sep = '')
sep - separator parameter, which will eliminate the space between name and comma.

Printing strings with print() in Python [duplicate]

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

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

Python Using (%s) in a string that slo contains a (%)? [duplicate]

This question already has answers here:
How can I selectively escape percent (%) in Python strings?
(6 answers)
Closed 8 years ago.
I have a string that contains a % that I ALSO want to use %s to replace a section of that string with a variable. Something like
name = 'john'
string = 'hello %s! You owe 10%.' % (name)
But when I run it, I get
not enough arguments for format string
I'm pretty sure that means that python thinks I'm trying to insert more than 1 variable into the string but only included the one. How do I overcome this? Thanks!
You can use a % in your string using this syntax, by escaping it with another %:
>>> name = 'John'
>>> string = 'hello %s! You owe 10%%.' % (name)
>>> string
'hello John! You owe 10%.'
More about: String Formatting Operations - Python 2.x documentation
As #Burhan added after my post, you can bypass this problem by using the format syntax recommended by Python 3:
>>> name = 'John'
>>> string = 'hello {}! You owe 10%'.format(name)
>>> string
'Hello John! You owe 10%'
# Another way, with naming for more readibility
>>> string = 'hello {name}! You owe 10%.'.format(name=name)
>>> str
'hello John! You owe 10%.'
In addition to what Maxime posted, you can also do this:
>> name = 'john'
>>> str = 'Hello {}! You owe 10%'.format(name)
>>> str
'Hello john! You owe 10%'

Python print_r which returns value instead of printing it

Is it possible, in Python, to do something similar to:
echo 'Content of $var is ', print_r($var, TRUE);
in PHP?
I have a variable var and I would like to assign its contents in a readable form to a string, for example:
str = 'Hello. '
str = str + var
You could simply use str(var), as in:
s = 'Hello. ' + str(var)
Here, str is a built-in function, and has nothing to do with the str you have in your script. When coding in Python, please avoid names that coincide with the names of built-in functions.
An alternative way is to use the string formatting operator %:
s = 'Hello. %s' % var
Three methods of achieving what you want
There are at least three ways of doing this in python:
The best one - using .format() method of string objects (available since Python 2.6):
Using simple replacement:
print 'Content of var is {}'.format(var)
Using referencing by name:
print 'Content of var is {var}'.format(**locals())
The always-working one - formatting operation:
Using simple replacement:
print 'Content of var is %s' % var
Using referencing by name:
print 'Content of var is %(var)s' % locals()
Concatenation:
print 'Content of var is ' + str(var)
Difference between %r and %s in formatting operations
%r differs from %s, because %r is replaced with representation of the variable, and %s is replaced with the variable converted to string. You can see it clearly on the example below:
>>> class MyClass():
def __str__(self):
return '__str__() result'
def __repr__(self):
return '__repr__() result'
>>> mc = MyClass()
>>> '%r' % mc
'__repr__() result'
>>> '%s' % mc
'__str__() result'
Did it help?
Is this what you are looking for?
import pprint
pprint.pprint(variable)
Note:
var = 'xxx'
s = 'Hello. %s' % var
print s

Categories

Resources