how to pad spaces to the right using %s in python? - python

in my program I have to organize stings to be of a certain length, in this case I set the max length to a. when I set it up the way I written below, I get an error in the python visualizer that I am using a unsupported format character. I can't use format or ljust to format my answer.
a =9
string = '%(a)s' % 'k'
print (string + 'KITE')
the problem is I know this will work if the variable a was a number, so what is going on?
edit- the desired out put would be ' kKITE'

EDIT:
If rjust is not allowed either:
>>> s = '%s' % (' '*8 + 'k')
>>> s + 'KITE'
' kKITE'
I believe you are looking for rjust:
>>> 'kKITE'.rjust(9)
' kKITE'
Or for your example:
>>> s = ('%s' % 'k').rjust(8)
>>> s + 'KITE'
' kKITE'

a = 9
string = "%s" %('k' * a)
print (string + 'KITE')
>> 'kkkkkkkkkKITE'
a = 9
string = "%s%s" %(' ' * a, 'k')
print (string + 'KITE')
>> ' kKITE'

Related

How to move a white space in a string?

I need to move a whitespace in a string one position to the right.
This is my code:
for i in range(0,len(resultaat)):
if resultaat[i] == " ":
string = resultaat[:i] + resultaat[i+1] + " " + resultaat[i+2:]
E.g.:
If resultaat =
"TH EZE NO FPYTHON."
Than my output needs to be:
'THE ZEN OF PYTHON.'
, but the output that I get is:
"TH EZE NO F PYTHON."
I think this happened because the loop undid the action where it moved the previous space.
I don't know how to fix this problem.
Can someone help me with this?
Thanks!
Each time through the loop you're getting slices of the original resultaat string, without the changes you've made for previous iterations.
You should copy resultaat to string first, then use that as the source of each slice so you accumulate all the changes.
string = resultaat
for i in range(0,len(resultaat)):
if resultaat[i] == " ":
string = string[:i] + string[i+1] + " " + string[i+2:]
You could do something like this:
# first get the indexes that the character you want to merge
indexes = [i for i, c in enumerate(resultaat) if c == ' ']
for i in indexes: # go through those indexes and swap the characters as you have done
resultaat = resultaat[:i] + resultaat[i+1] + " " + resultaat[i+2:] # updating resultaat each time you want to swap characters
Assuming the stated input value actually has one more space than is actually needed then:
TXT = "TH EZE NO FPYTHON."
def process(s):
t = list(s)
for i, c in enumerate(t[:-1]):
if c == ' ':
t[i+1], t[i] = ' ', t[i+1]
return ''.join(t)
print(process(TXT))
Output:
THE ZEN OF PYTHON.

Python value assignment does not print

I'm a student and have a question. I'm not getting the correct output in our textbook.
first = 'I'
second = 'love'
third = 'Python'
sentence = first + '' + second + '' + third + '.'
Output:
I love Python.
When I run it, nothing happens. Can someone explain why? Thanks in advance!
print sentence. Will print the outut
But from what you have this will output "IlovePython." not I love Python.
This is because ther is no space between your '' tags. To fix this convert all those '' to ' '. Save the last one, which is . as it should be.
Your sentence variable should be:
sentence = first + ' ' + second + ' ' + third + '.'
and after assigning the value to sentence you have to print it:
print (sentence)
Also you can print directly the concatenation without saving it into a variable:
print (first + ' ' + second + ' ' + third + '.')

Printing string with multiple placeholder formatters in Python 2.7

I'm trying to make an algorithm in Python 2.7.10 that takes user input, splits it and puts words into a list, then takes all words from that list and prints them in a specific manner.
usr_input = raw_input(' > ')
input = usr_input.split(' ')
print "You think that the painting is:"
print "%s" + ", %s" * len(input) + "." % ( > ? < )
The %s formatters work as placeholders. The problem is that the number of placeholders that will be printed as a part of the string isn't fix, it's equal to len(input). Therefore I don't know how to assign values to these formatters. (That's the " > ? < " part inside of the brackets.)
Note: as this is for test purposes only, let's assume the user will only be inputting strings, not integers, etc. so that there is no need for the %r formatter.
The desired output should look somewhat like this:
> nice pretty funny
You think that the painting is:
nice, pretty, funny.
I know this can be achieved using the str.join(str) method but is there a way of doing it as I explained above? Thanks.
Use print ("%s" + ", %s" * (len(input) - 1) + ".") % tuple(input)
However, IMO ', '.join(input) + '.' is better :)
You can do what you want by doing this:
print ",".join(["%s"] * len(input)) % tuple(input)
Basically, construct your string of "%s, "... and pass the input as a list to the string formatters. You can do it exactly like you've written it too, just pass in your list.
print "%s" + ", %s" * len(input)) + "." % tuple(input)
You should use a tuple after "%". Note that you have already considered the first word in the print, so len(input) -1 words are left to be written.
usr_input = raw_input(' > ')
input = usr_input.split(' ')
output = "%s" + ", %s" * (len(input) - 1) + "."
print "You think that the painting is:"
print output % tuple(input)

error defining a string

I am trying to make a program that adds a number to a string and prints it. Here is my code:
n1 = 5
n2 = 6
statement = "number 1: ",n1,") (number 2: ",n2,")"
print(statement)
I want it to print (number1: 5 ) * (number2: 6 ).
EDIT:
The problem I had was my items were separated by commas, not plus signs. This caused an error becuase you need to seperate things with plus signs.
3 ways to get around this would be:
A:% formatting
number = 1
statement = "Your number is %s." % (number)
B:{} formatting
number = 2
statement = "Your number is {}.".format(number)
C:Converting to a string
number = 3
statement = "Your number is "+str(number) + "."
You are trying to join strings using the comma operator. This creates a tuple, not a string. Strings are concatenated using the + operator, like so:
statement = "(x +" + str(n1) + ") * (x +" + str(n2) + ")"
But it would be even easier to use the string formatting operators:
statement = "(x + {}) * (x + {})".format(n1,n2)
or
statement = "(x + %s) * (x + %s)" % (n1, n2)
Your syntax in line 4, where you build the statement, is one that constructs a list from comma-separated elements. You need to convert the integers to strings somehow, and work in the spaces you want. Here's the closest equivalent, I think:
statement = "(x + " + str(n1) + " ) * (x + " + str(n2) + " )"
This prints the output you requested.
When you construct your "statement" variable, you are building a tuple, not a string (those commas are the culprit).
Build that variable as a string, and you'll be able to add it to the other string.
statement = "(x + {n1}) * x +{n2})".format(n1=n1, n2=n2)

Convert strings to int or float in Python 3?

integer = input("Number: ")
rslt = int(integer)+2
print('2 + ' + integer + ' = ' + rslt)
double = input("Point Number: ")
print('2.5 + ' +double+' = ' +(float(double)+2.5))
Gives me
Traceback (most recent call last):
File "C:\...", line 13, in <module>
print('2 + ' + integer + ' = ' + rslt)
TypeError: Can't convert 'int' object to str implicitly
I'm fairly new to programming and my background is mostly just the basics of C# so far. I wanted to try to learn Python through doing all my C# school projects on Python. I'm used to the simple syntax of C# which would look something like this:
int integer = Convert.ToInt32(Console.ReadLine())
or
double double = Convert.ToDouble(Console.ReadLine())
Which takes a user input string and converts it to what I specified.
I think I read py2.x has a command called raw_input that works a bit better than the input command of py3.x in this regard.
I was trying to find myself a similar format as the one I'm used to in C# to use in Python, but it's proving surprisingly hard just to find a method to convert the user input string into an integer after all this googling and trying everything I could think of (and that I found on google) I decided it was time to ask. Can you help?
You have to convert the integer into a string:
print('2 + ' + str(integer) + ' = ' + str(rslt))
Or pass it as an argument to print and print will do it for you:
print('2 +', integer, '=', rslt)
I would do it using string formatting:
print('2 + {} = {}'.format(integer, rslt))
Your problem is not with converting the input to an integer. The problem is that when you write ' = ' + rslt you are trying to add an integer to a string, and you can't do that.
You have a few options. You can convert integer and rslt back into strings to add them to the rest of your string:
print('2 + ' + str(integer) + ' = ' + str(rslt))
Or you could just print multiple things:
print('2 + ', integer, ' = ', rslt)
Or use string formatting:
print('2 + {0} = {1}'.format(integer, rslt))
In Python 3.x - input is the equivalent of Python 2.x's raw_input...
You should be using string formatting for this - and perform some error checking:
try:
integer = int(input('something: '))
print('2 + {} = {}'.format(integer, integer + 2))
except ValueError as e:
print("ooops - you didn't enter something I could make an int of...")
Another option - that looks a bit convoluted is to allow the interpreter to take its best guess at the value, then raise something that isn't int or float:
from ast import literal_eval
try:
value = literal_eval(input('test: '))
if not isinstance(value, (int, float)):
raise ValueError
print value + 2
except ValueError as e:
print('oooops - not int or float')
This allows a bit more flexibility if you wanted complex numbers or lists or tuples as input for instance...
If you want to convert a value to an integer, use the int built in function, and to convert a value to a floating point number, use the float built in function. Then you can use the str built in function to convert those values back to strings. The built in function input returns strings, so you would use these functions in code like this:
integer = input("Number: ")
rslt = int(integer)+2
print('2 + ' + integer + ' = ' + str(rslt))
double = input("Point Number: ")
print('2.5 + ' +str(double)+' = ' +str(float(double)+2.5)
integer = int(input("Number: "))
print('2 + %d = %d' % (integer, integer + 2))
double = float(input("Point Number: "))
print('2.5 + %.2f = %.2f' % (double, double + 2.5))

Categories

Resources