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.
Related
This question already has answers here:
Why do backslashes appear twice?
(2 answers)
Closed 2 years ago.
So I have a function that takes a string, iterates over a set of characters and returns a string with a backslash added to all the occurences of any character in that particular string:
def re_escape(string):
res = "|\^&+\-%*/=!>"
for i in res:
if i in string:
a = string.split(i)
adjusted = ""
for y in a:
adjusted+="\\"+i+y
adjusted = adjusted[2:]
string = adjusted
print(string)
return string
Giving this function the string " <br>" returns " <br\>", as desired.
However, going back to the part of the program calling this function and receiving the string as a return value, trying to print it results in " <br\\>" being printed. Is there any way to prevent it from adding the second undesired backslash?
Give it a try: string.replace('\\\\','\\').
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
I'd like to specify a string with both line continuation and catenation characters. this is really useful if I'm echoing a bunch of related values. Here is a simple example with only two parameters:
temp = "here is\n"\
+"\t{}\n"\
+"\t{}".format("foo","bar")
print(temp)
here's what I get:
here is
{}
foo
And here is what I expect:
here is
foo
bar
What gives?
You can try something like this :
temp = ("here is\n"
"\t{}\n"
"\t{}".format("foo","bar"))
print(temp)
Or like :
# the \t have been replaced with
# 4 spaces just as an example
temp = '''here is
{}
{}'''.format
print(temp('foo', 'bar'))
vs. what you have:
a = "here is\n"
b = "\t{}\n"
c = "\t{}".format("foo","bar")
print( a + b + c)
str.format is called before your strings are concatenated. Think of it like 1 + 2 * 3, where the multiplication is evaluated before the addition.
Just wrap the whole string in parentheses to indicate that you want the strings concatenated before calling str.format:
temp = ("here is\n"
+ "\t{}\n"
+ "\t{}").format("foo","bar")
Python in effect sees this:
Concatenate the result of
"here is\n"
with the resuslt of
"\t{}\n"
with the result of
"\t{}".format("foo","bar")
You have 3 separate string literals, and only the last one has the str.format() method applied.
Note that the Python interpreter is concatenating the strings at runtime.
You should instead use implicit string literal concatenation. Whenever you place two string literals side by side in an expression with no other operators in between, you get a single string:
"This is a single" " long string, even though there are separate literals"
This is stored with the bytecode as a single constant:
>>> compile('"This is a single" " long string, even though there are separate literals"', '', 'single').co_consts
('This is a single long string, even though there are separate literals', None)
>>> compile('"This is two separate" + " strings added together later"', '', 'single').co_consts
('This is two separate', ' strings added together later', None)
From the String literal concatenation documentation:
Multiple adjacent string or bytes literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld".
When you use implicit string literal concatenation, any .format() call at the end is applied to that whole, single string.
Next, you don't want to use \ backslash line continuation. Use parentheses instead, it is cleaner:
temp = (
"here is\n"
"\t{}\n"
"\t{}".format("foo","bar"))
This is called implicit line joining.
You might also want to learn about multiline string literals, where you use three quotes at the start and end. Newlines are allowed in such strings and remain part of the value:
temp = """\
here is
\t{}
\t{}""".format("foo","bar")
I used a \ backslash after the opening """ to escape the first newline.
The format function is only being applied to the last string.
temp = "here is\n"\
+"\t{}\n"\
+"\t{}".format("foo","bar")
Is doing this:
temp = "here is\n" + "\t{}\n"\ + "\t{}".format("foo","bar")
The key is that the .format() function is only happening to the last string:
"\t{}".format("foo","bar")
You can obtain the desired result using parentheses:
temp = ("here is\n"\
+"\t{}\n"\
+"\t{}").format("foo","bar")
print(temp)
#here is
# foo
# bar
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
This question already has answers here:
Is there a Python equivalent to Ruby's string interpolation?
(9 answers)
Closed 8 years ago.
In Ruby I can do this:
"This is a string with the value of #{variable} shown."
How do I do that same thing in Python?
You have a lot of options.
"This is a string with the value of " + str(variable) + " shown."
"This is a string with the value of %s shown." % (str(variable))
"This is a string with the value of {0} shown.".format(variable)
The modern/preferred way is to use str.format:
"This is a string with the value of {} shown.".format(variable)
Below is a demonstration:
>>> 'abc{}'.format(123)
'abc123'
>>>
Note that in Python versions before 2.7, you need to explicitly number the format fields:
"This is a string with the value of {0} shown.".format(variable)
this is one of the way we can also do
from string import Template
s = Template('$who likes $what')
s.substitute(who='tim', what='kung pao')