I'm trying to output the following two lines of text:
The city with the most contracts is:
Chicago (2500 contracts)
this is the code I'm using:
a = 'Chicago'
b = 2500
print('The city with the most contracts is:')
print(a, b, 'contracts)')
the current output is:
The city with the most contracts is:
Chicago 2500 contracts)
How can I add a parenthesis before the number 2500?
I tried adding the parenthesis as a string, as in:
print('The city with the most contracts is:')
print(a, '(', b, 'contracts)')
but it adds an unwanted space between the parenthesis and the number 2500, looks like this:
The city with the most contracts is:
Chicago ( 2500 contracts)
The easiest way is with a formatting string.
print(f'{a} ({b} contracts)')
To handle manually the issue, you'd do
print(a, '(' + str(b), 'contracts)')
But you'd rather use the formatting solutions
print(f'{a} ({b} contracts)')
print('{} ({} contracts)'.format(a, b))
print('%s (%s contracts)' % (a, b))
For Python 3.6+:
print(f"{a} ({b} contracts)")
For a prior version:
print("{a} ({b} contracts)".format(a=a, b=b))
or
print("{} ({} contracts)".format(a, b))
I will not encourage to format using %.
This worked for me using string formatting
a = 'Chicago'
b = 2500
print("The city with the most contracts is:")
print("{} ({} contracts)".format(a,b))
This should work:
a = 'Chicago'
b = 2500
print('The city with the most contracts is:')
print(a + ' (' + str(b) + ' contracts)')
Use the plus sign instead of the comma.
a = "Chicago"
b = 2500
print(a + ' (' + str(b) + ' contracts)')
The output was:
Chicago (2500 contracts)
Related
I'm trying to write a program for a computer programming course to calculate the area of a triangle, and the expected output is "The area is [insert number here]."
Here's what I have, and I'm frankly stumped on the full stop:
b = input('Base: ')
h = input('Height: ')
a = 0.5 * float(b) * float(h)
print('The area is', a, '.')
It outputs this:
Base: 1
Height: 1
The area is 0.5 .
This is marked as incorrect because of the extra space, how do I get rid of it?
The print default separator argument is ' ' (a space), so try changing that to '' (empty string):
print('The area is ', a, '.', sep='')
Or use + and make it a string:
print('The area is ', str(a) + '.')
Best with string formatting:
f string literal:
print(f'The area is {a}.')
Or %s:
print('The area is %s.' % a)
Or str.format:
print('The area is {}.'.format(a))
I am only three weeks into my Intro to Programming course, so bear with me!
I am writing a code as follows:
number1 = input('Enter the first number: ')
number1 = int(number1)
number2 = input('Enter the second number: ')
number2 = int(number2)
number3 = input('Enter the third number: ')
number3 = int(number3)
ratio12 = int(number1 / number2)
ratio13 = int(number1 / number3)
ratio23 = int(number2 / number3)
print('The ratio of', + number1, '+', + number2,'is', + ratio12, '.')
print('The ratio of', + number1, '+', + number3,'is', + ratio13, '.')
print('The ratio of', + number2, '+', + number3,'is', + ratio23, '.')
The code is functional (finally), but I can't seem to get rid of the space before the period on the print statements. Is there a way that I can do that?
The reason why this happens is because you are using commas in your print statements. In python there are a few ways to give the print statement multiple variables, you seem to be mixing two of them together. The ways are as follows.
Concatenate the string.
print('The ratio of ' + str(number1) + ' + ' + str(number2) + ' is ' + str(ration12) + '.')
This way is probably the most basic way. It will join the strings without adding any characters in between them (e.g. no spaces in between unless you add them explicitly.) Also note, that string concatenation won't automatically cast the integers to a string for you.
Pass print multiple arguments.
print('The ratio of', number1, '+', number2, 'is', ration12, '.')
This will automatically add spaces between each argument and is what is happening in your case. The separator (which defaults to a space) can be changed by passing a keyword argument to the print function. For example, print('i = ', i, sep='')
Use string formatting.
print('The ratio of {} + {} is {}.'.format(number1, number2, ratio12))
This way is the most readable and often the best way. It will replace the '{}' sections in you 'template' string with the arguments based into the format function. It does this in order, however you can add an index like this '{0}' to explicitly use an argument by index.
Some string formating makes your live easier:
number1 = 1
number2 = 2
ratio12 = number1 / number2
print('The ratio of {} + {} is {}.'.format(number1, number2, ratio12))
Output:
The ratio of 1 + 2 is 0.5.
You can control the "separator" using the sep argument to print:
print('The ratio of', + number1, '+', + number2,'is', + ratio12, '.', sep='')
Note that this will change the spacing between the other items as well.
Also -- You don't need the extra + operators in there. Here's a version without the spaces and with explicit spaces added where I think you want them:
print('The ratio of ', number1, ' + ', number2, ' is ', ratio12, '.', sep='')
You're confused about the concatenation function and print fields. If you're going to concatenate all those strings, just use concatenation. The comma includes the default separator.
print('The ratio of', number1, '+', number2,'is', str(ratio12) + '.')
Try to write to it this way:
print('The ratio of %d + %d is %d.' %(number1, number2, ratio12))
print('The ratio of %d + %d is %d.' %(number1, number3, ratio13))
print('The ratio of %d + %d is %d.' %(number2, number3, ratio23))
That's the way print works when you give it multiple comma separated arguments. The logic behind that is that when you quickly want to print a bunch of variables, it's a pain to manually add widespace.
Well, one thing to try: Get rid of all the , in the print statement. You can just chain strings using the + sign.
So,
print('The ratio of ' + str(number1) + ' ' + str(number2) + ' is ' + str(ratio12) + '.')
If you need even greater control over formatting, you'd want to look into the format function.
print("The ratio of {} + {} is {}.".format(number1, number2, ratio12))
This Code Works Fine.....But it's like static.
I don't know what to do to make it work in dynamic way?
I want:-
When user inputs 3 number of cities it should give
a="You would like to visit "+li[0]+" as city 1 and " +li[1]+ " as city
2 and "+li[2]+" as city 3 on your trip"
Similaraly when input is 5 cities it should go to 5 times
li = []
global a
number_of_cities = int(raw_input("Enter Number of Cities -->"))
for city in range(number_of_cities):
li.append(raw_input("Enter City Name -->"))
print li
a="You would like to visit "+li[0]+" as city 1 and " +li[1]+ " as city 2 and "+li[2]+" as city 3 on your trip"
print a
a = a.split(" ")
print "\nSplitted First Sentence looks like"
print a
print "\nJoined First Sentence and added 1"
index = 0
for word in a:
if word.isdigit():
a[index] = str(int(word)+1)
index += 1
print " ".join(a)
You should do something like this
a = 'You would like to visit ' + ' and '.join('{0} as city {1}'.format(city, index) for index, city in enumerate(li, 1)) + ' on your trip'
You can build the string with a combination of string formatting, str.join and enumerate:
a = "You would like to visit {} on your trip".format(
" and ".join("{} as city {}".format(city, i)
for i, city in enumerate(li, 1)))
str.join() is given a generator expression as the iterable argument. The curly braces ({}) in the strings are replacement fields (placeholders), which will be replaced by positional arguments when formatting. For example
'{} {}'.format('a', 'b')
will produce the string "a b", as will
# explicit positional argument specifiers
'{0} {1}'.format('a', 'b')
create another for loop and save your cities to an array. afterwords, concat the array using "join" and put put everything inside the string:
cities = []
for i in range(0,len(li), 1):
cities.append("%s as city %i" % (li[i], i))
cities_str = " and ".join(cities)
a = "You would like to visit %s on your trip" % (cities_str) # edited out the + sign
How can I join a data below,
# Convert Spark DataFrame to Pandas
pandas_df = df.toPandas()
print pandas_df
age name
0 NaN Michael
1 30 Andy
2 19 Justin
My current attempt,
persons = ""
for index, row in pandas_df.iterrows():
persons += str(row['name']) + ", " + str(row['age']) + "/ "
print row['name'], row['age']
print persons
Result,
Michael, nan/ Andy, 30.0/ Justin, 19.0/
But I am after (no slash at the end),
Michael, nan/ Andy, 30.0/ Justin, 19.0
If you want to keep your method of looping through each , then you can simply remove the last / by doing rstrip() on it to strip from the right side. Example -
persons = ""
for index, row in pandas_df.iterrows():
persons += str(row['name']) + ", " + str(row['age']) + "/ "
print row['name'], row['age']
person = person.rstrip("/ ")
print persons
Example/Demo -
>>> person = "Michael, nan/ Andy, 30.0/ Justin, 19.0/ "
>>> person = person.rstrip('/ ')
>>> person
'Michael, nan/ Andy, 30.0/ Justin, 19.0'
But if you really do not want the print row['name'], row['age'] inside the loop, then you can convert this into a generator function and let str.join() handle what you want. Example -
person = "/".join(",".join([str(row['name']), str(row['age'])]) for _, row in pandas_df.iterrows())
I think this will do
persons = []
str_pearsons=""
for index, row in pandas_df.iterrows():
persons.append( str(row['name']) + ", " + str(row['age']))
str_pearsons="/ ".join(persons)
You can achieve this easily in a one liner that will be vectorised:
In [10]:
'/ '.join(df['name'] + ', ' + df['age'].astype(str))
Out[10]:
'Michael, nan/ Andy, 30.0/ Justin, 19.0'
I have to add str(iterMul(a,b)) to obtain what I want. Is it the proper way to do it?
def iterMul(a,b):
result = 0
while b > 0:
result += a
b -=1
return result
a=int(raw_input('Enter an integer: '))
print('')
b=int(raw_input('Enter an integer: '))
print('')
print (str(a) + ' times '+str(b)+' is equal to '+ str(iterMul(a,b)))
Thanks in advance!
Use string formatting instead:
print '{0} times {1} is equal to {2}'.format(a, b, iterMul(a,b))
String formatting automatically transforms integers to string when interpolating the values, and is more readable than print value, ' some text ', othervalue, ' more text and ', thirdvalue.