I'm new to Python, and I'm wondering how to print multiple values without having the extra space added in between. I want the output ab rather than a b without having to call print twice:
print("a", end="")
print("b")
Also, I have the following code:
a = 42
b = 84
and I want to print their values as a = 42, b = 84, yet if I do
print("a = ", a, ", ", b = ", b)
extra spaces are added (it outputs a = 42 , b = 84)
Whereas the Java style,
print("a = " + a + ", b = " + b)
raises a TypeError.
You can use the sep parameter to get rid of the spaces:
>>> print("a","b","c")
a b c
>>> print("a","b","c",sep="")
abc
I don't know what you mean by "Java style"; in Python you can't add strings to (say) integers that way, although if a and b are strings it'll work. You have several other options, of course:
>>> print("a = ", a, ", b = ", b, sep="")
a = 2, b = 3
>>> print("a = " + str(a) + ", b = " + str(b))
a = 2, b = 3
>>> print("a = {}, b = {}".format(a,b))
a = 2, b = 3
>>> print(f"a = {a}, b = {b}")
a = 2, b = 3
The last one requires Python 3.6 or later. For earlier versions, you can simulate the same effect (although I don't recommend this in general, it comes in handy sometimes and there's no point pretending otherwise):
>>> print("a = {a}, b = {b}".format(**locals()))
a = 2, b = 3
>>> print("b = {b}, a = {a}".format(**locals()))
b = 3, a = 2
The actual syntax of the print() function is
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
You can see it has an arg sep with default value ' '. That's why space gets inserted in between.
print("United","States") #Output: United States
print("United","States",sep="") #Output: UnitedStates
You can also use
print("%d%d" %(a,b))
to print a and b not seperated by spaces in form of a formatted string. This is similar to the one in c.
To separate the strings or values you can use sep parameter in print()
print(a,b,sep='')
print() will automatically make spaces between arguments.
>>> print("a", "b", "c")
a b c
To have more control over spacing, you could use string formatting:
>>> v0, v1, v2 = "a", "b", "c"
>>> print("%s%s%s" % (v0, v1, v2))
abc
>>> print("%s%s%s".format(v0, v1, v2)
abc
>>> print(f"{v0}{v1}{v2}")
abc
I like this guide on the subject: https://realpython.com/python-f-strings/
On this page the answer is to print your normal text and at the end to use
sep="".
So the command
print("Hole", hole, "Par", par, sep="")
will give
"Hole1Par4"
assuming that hole==1 and par==4.
Related
I have a variable A equal to :
A = '$\\epsilon_1$\n'
When we print the variable, we are obtaining this :
print(A)
$\epsilon_1$
How can I store this output on a variable?
From A, I want B equal to :
B = '$\epsilon_1$'
Thank you!
Strip off the \n from A and assign it to B.
A = '$\\epsilon_1$\n'
B = A.strip('\n')
print(f'B: {B}')
# Output:
# B: $\epsilon_1$
I'm trying to find different words in 2 different sentence and my sentences inside of Excel's A row and B row.
def UncommonWords(A, B):
res = len(test_string.split())
count = {}
for word in A.split():
count[word] = count.get(word, 0) + 1
for word in B.split():
count[word] = count.get(word, 0) + 1
return [word for word in count if count[word] == 1]
A = "wu tang clan"
B = "wu tang can"
print(UncommonWords(A, B))
print(A,'=',B)
A = "wu tang clan"
B = "wu tang can"
I have A and B sentences. As you can see 'clan' and 'can' words different.
I need an output like:
clan=can
So I dont want to match not unique words. And my A and B sentences always gonna change because i will get my sentences from Excel but my code just return me
wu tang clan=wu tang can
in my code return part give me an output like ['clan'],['can'] but this not seperated. I thought if i can seperate them like that
'A sentence unique word: clan' as dif1
'B sentence unique word: clan' as dif2
i will put dif1 and dif2 to print(dif1,'=',dif2)
probably my output will ['clan=can'] and its so fine for me. By the way sorry for my English, thank you for helps.
Edit1:
Specific examples:
A = "put returns between two sentence"
B = "put returns bet ween 2 sentence"
Output should be like: between two = bet ween 2
So i have to find unique words in A with in order then find in B, after that output should be as above.
Edit2:
A = "a breath before surfacing"
B = "a be before sura"
Output should be like: breath=be|surfacing=sura
uncommon_word_in_A[0] ?= uncommon_word_in_B[0]
uncommon_word_in_A[1] ?= uncommon_word_in_B[1]
The result you get is to be expected since you print your arguments instead of printing the result of the function (noticed the return statement at the end of the function ?). You'd want something like:
result = UncommonWords(A, B)
print("{} = {}".format(result[0], result[1])
but this blindly assumes you always have exactly one word of difference between your two strings - which will certainly not be the case for real data.
Also, your code is very inefficient. Using the builtin set type and it's symmetric_difference operation gives the same result in much less time and much less code:
print(set(A).symmetric_difference(set(B)))
Oh and yes, Python's naming conventions are all_lower for variables, functions and modules and CamelCase for classes.
Here is sample code for your reference
def UncommonWords(A, B):
A = A.split()
B = B.split()
uncommon = [(A[i],B[i]) for i in range(0,len(A)) if not str(A[i])==str(B[i])]
return uncommon
A = "wu tang clan"
B = "wu tang can"
uncommon = UncommonWords(A, B)
print(['='.join([i[0],i[1]]) for i in uncommon])
Hope this helps
def UncommonWords(A, B):
A_list=A.split()
B_list=B.split()
uncommon_word_in_A = []
uncommon_word_in_B = []
i = 0
for word in A_list:
if word not in B_list:
uncommon_word_in_A.append(word)
for word2 in B_list:
if word2 not in A_list:
uncommon_word_in_B.append(word2)
for i in range(0, len(uncommon_word_in_A)):
print(uncommon_word_in_A[i], end=" ")
print("=", end=" ")
for i in range(0, len(uncommon_word_in_B)):
print(uncommon_word_in_B[i], end=" ")
A = "put returns between two sentence"
B = "put returns bet ween 2 sentence"
UncommonWords(A, B)
Output:
between two = bet ween 2
So a typical way to assign arguments to a variable in python is:
variable_name = "argument name as a string"
or
variable_name = 1
With 'argv' or return in a function, the whole syntax is inverted:
argument_name1, argument_name2 = argv
or
def function_name(a):
a = 1
b = a + 1
return a, b
a, b = function(1)
What's the deal with this inversion? Is it something I need to remember, or is there a logic behind this that can be applied to more things?
There is no inversion in your examples.
The = sign assigns whatever is on the right of it to whatever is on the left to it.
Here, you assign values to a new variable:
variable_name = "argument name as a string"
variable_name = 1
In the function, you assign the output of the function (right) to the variables on the left:
def function_name(a):
a = 1
b = a + 1
return a, b
a, b = function_name(1)
If your confusion comes from the comma, it basically allows you to assign two variables at the same time.
function_name(1) returns (a,b)
a, b = function_name(1)
is simply short for:
output = function_name(1) # Output is (a, b)
a = output[0]
b = output[1]
However, I think you are confused about the general concept of assignment. The function takes an argument a, but then overrides the argument with 1.
It should be either:
def function_name():
a = 1
b = a + 1
return a, b
or
def function_name(a):
b = a + 1
return a, b
Here is how you can test your claim that you are assigning from left to right:
argument_name1 = 'a'
argument_name2 = 'b'
argument_name1, argument_name2 = argv
print argv
Will throw the error NameError: name 'argv' is not defined
But:
argv = ('a', 'b')
argument_name1, argument_name2 = argv
print(argument_name1, argument_name2)
prints: a b
The syntax is not inverted. Python actuallly allows you to unpack the variable on the fly. The function actually returns a tuple
def function_name(a):
a = 1
b = a + 1
return a, b
If you test the function return type, you get:
>>> type(function_name(1))
<type 'tuple'>
This syntax actually prevents you from wirting this
value = function_name(1) # value = (1, 2)
a = value[0] # a = 1
b = value[1] # b = 2
Expected output: report_exam_avg(100, 95, 80) == 'Your average score: 91.7'
def report_exam_avg(a, b, c):
assert is_number(a) and is_number(b) and is_number(c)
a = float(a)
b = float(b)
c = float(c)
mean = (a + b + c) / 3.0
mean = round(mean,1)
x = 'Your average score: ', mean
return x
Actual output: ('Your average score: ', 91.7)
Note: cant unpack the tuple such as below because I need the sentence returned not printed
avg, score = report_exam_avg(100, 95, 80)
print(avg, score)
You are returning x as a tuple in this case. So this is why when you simply print x you get a tuple as output. You should either use the print statement in Function or modify function as follows:
def report_exam_avg(a, b, c):
assert is_number(a) and is_number(b) and is_number(c)
a = float(a)
b = float(b)
c = float(c)
mean = (a + b + c) / 3.0
mean = round(mean,1)
x = mean
return x
So your call to function would be:
print ("Your Avg. Score:", report_exam_avg(100, 95, 80))
I would suggest changing the use of the comma to plus. This would change where you set the variable x:
x = 'Your average score: ' + str(mean)
This will properly handle string concatenation, whereas the comma will generate a tuple.
Additionally, if you are using python 3.6, you could make use of fstrings, a very handy string interpolation tool. This would change the line to look like this:
x = f'Your average score: {mean}'
You can then return x in string form.
Python supports return multiple values in a function, just delimit them with ,. In your case, Python thinks you'are doing this, thus returns a tuple.
To return a string, simply concat string with +:
x = 'Your average score: ' + str(mean)
return x
Or, use string format
x = 'Your average score: {}'.format(mean)
return x
For example
s = "a b c d e f "
Needs to be reduced to
s = "a b c d e f "
Right now I do something like this
for i in xrange(arbitrarilyHighNumber,1,-1):
s = s.replace(" "*i," ")
But I want to make it more dynamic and Pythonic (and assume any number of spaces, too). How can I replace every contiguous space threshold with a single space?
You can use re.sub:
>>> import re
>>> s = "a b c d e f "
>>> re.sub('\s{2,}', ' ', s)
'a b c d e f '
>>>
\s{2,} matches two or more whitespace characters.
Since the regular expression answer has already been given. You could also do it with iterative replacements.
while s.find(" ") is not -1:
s = s.replace(" ", " ")
My original answer of splitting and rejoining gets rid of the leading and trailing whitespaces
' '.join(s.split())