how can get a desired amount of whitespaces in a print
print("a",'','','','','','',"a")
can not be written as
print("a",''*6,"a")
does not work. Please help
'' is a null string, not a space. In the first example, print itself is inserting a space between each of the 8 arguments; in the second, it's inserting a space between each of the 3 arguments.
If you want
a a
you can use
print('a', ' '*4, 'a') # a, space, 4-spacces, space, a
or
print('a', 'a', sep=' '*6) # a separator of 6 spaces
or simply
print('a a')
You can use the sep keyword
print("a", "a", sep=" "*6)
prints
a a
I think you can do it likethis :
print("a"," "*6,"a")
Related
Suppose I want to read a sequence of inputs, where each input is a tuple is of the form <string> , <integer>, <string>. Additionally, there can be arbitrary amount of whitespace around the commas. An easy way to do this in C/C++ is to use scanf with format string "%s , %d , %s". What is the equivalent function in python?
Suppose we knew that each input is on a separate line, then you could easily parse this in python using split and strip. But the newline requirement complicates things. Furthermore, we could even have weird inputs such as
<s11>, <i1>
, <s12> <s21>,
<i2> , <s22>
Where s11, i1, s12 is the first input and s21, i2, s22 is the second. And scanf would still be able to handle this. How does one do it in python? I also don't want to take the entire input at once and parse it, since I know that there will be other inputs that don't fit this format later on, and I don't want to do the parsing manually.
You should be able to first strip the whitespace, then split on commas, then handle the resulting strings and integers however you want. The regular expression s\+ matches any nonzero amount of whitespace characters:
input_string = " hello \n \t , 10 , world \n "
stripped_string = re.sub('\s+', '', input_string)
substrings = stripped_string.split(',')
string1 = substrings[0]
integer1 = int(substrings[1])
string2 = substrings[2]
You'd just have to put those last three lines inside a loop if you need to handle multiple s,i,s tuples in a row.
EDIT: I realize now you want to interpret any whitespace as a comma. I'm not sure how wise that is, but a hacky way to do it is to replace all the commas with whitespace, split on whitespace, and call it a day
input_string = " hello \n \t , 10 world \n "
stripped_string = re.sub(',', ' ', input_string)
substrings = stripped_string.split()
string1 = substrings[0]
integer1 = int(substrings[1])
string2 = substrings[2]
For delimited format it's pretty easy with the csv module.
You can plugin any kind of file-like inputs to it.
And you handle stripping white spaces and type casting downstream. Here's a sample to get you going:
In [25]: import fileinput
In [26]: import csv
In [28]: reader = csv.reader(fileinput.input())
In [29]: for l in reader:
...: print(l)
...:
stdin input -> a,b, c, d
print output -> ['a', 'b', ' c', ' d ']
This is my code:
class Student(Person):
def __init__(self, firstName, lastName, idNumber,scores):
self.firstName = firstName
self.lastName = lastName
self.idNumber = idNumber
self.testscores = scores
def calculate(self):
average = sum(self.testscores) / len(self.testscores)
if average>=90 and average<=100 :
return'O'
elif average>=80 and average<90 :
return'E'
elif average>=70 and average<80 :
return'A'
elif average>=55 and average<70 :
return'P'
elif average>=40 and average<55 :
return'D'
else:
return'T'
The statement : print("Grade: ", s.calculate()) returns Grade: O (two spaces) instead of Grade: O (single space).
Since the above print statement is in locked stub code I can't modify it.
Is there anyway I can remove the extra space while returning from calculate function?
Edit: For better understanding of the problem consider this
image
in which the only difference is in my output's and expected output's third statement because of additional space.
The print function prints each of its arguments with a space as a delimiter already, so by adding a space in "Grade: ", you're making it print another space between the colon and the grade. Simply replace "Grade: " with "Grade:" and it will output without the extra space.
You can specify sep='', i.e. an empty string:
print('Grade: ', s.calculate(), sep='')
Or you can remove the space from your first argument:
print('Grade:', s.calculate())
Alternatively, you can use string formatting:
print(f'Grade: {s.calculate()}') # 3.6+
print('Grade: {}'.format(s.calculate())) # pre-3.6
To troubleshoot such problems, you can use the built-in help, which tells you the default argument for sep is a single space:
help(print)
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
...
sep: string inserted between values, default a space.
...
Interestingly, the official docs have got it wrong:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Print objects to the text stream file, separated by sep and followed
by end. sep, end, file and flush, if present, must be given as keyword
arguments.
Since the above print statement is in locked stub code I can't modify it.
Is there anyway I can remove the extra space while returning from calculate function?
If I not misunderstand, you can change caculate function, but not print, and you want just see one space in output, and you are in python3.
Then you can use backspace \b, change E.g. return 'O' to return '\bO', and other return need to be changed also.
A simple code for your quick test:
def fun():
return 'O'
def fun2():
return '\bO'
print("Grade: ", fun())
print("Grade: ", fun2())
Hopefully, the community might explain this better to me. Below is the objective, I am trying to make sense of this code given the objective.
Objective: Initialize your list and read in the value of followed by lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list.
Sample input:
12
insert 0 5
insert 1 10
etc.
Sample output:
[5, 10]
etc.
The first line contains an integer, n, denoting the number of commands.
Each line of the subsequent lines contains one of the commands described above.
Code:
n = int(raw_input().strip())
List = []
for number in range(n):
args = raw_input().strip().split(" ")
if args[0] == "append":
List.append(int(args[1]))
elif args[0] == "insert":
List.insert(int(args[1]), int(args[2]))
So this is my interpretation of the variable "args." You take the raw input from the user, then remove the white spaces from the raw input. Once that is removed, the split function put the string into a list.
If my raw input was "insert 0 5," wouldn't strip() turn it into "insert05" ?
In python you use a split(delimiter) method onto a string in order to get a list based in the delimiter that you specified (by default is the space character) and the strip() method removes the white spaces at the end and beginning of a string
So step by step the operations are:
raw_input() #' insert 0 5 '
raw_input().strip() #'insert 0 5'
raw_input().strip().split() #['insert', '0', '5']
you can use split(';') by example if you want to convert strings delimited by semicolons 'insert;0;5'
Let's take an example, you take raw input
string=' I am a coder '
While you take input in form of a string, at first, strip() consumes input i.e. string.strip() makes it
string='I am a coder'
since spaces at the front and end are removed.
Now, split() is used to split the stripped string into a list
i.e.
string=['I', 'am', 'a', 'coder']
Nope, that would be .remove(" "), .strip() just gets rid of white space at the beginning and end of the string.
I have to print out every third letter of a text with spaces between and none at the end. I can do everything but the spaces between each of the letters.
Here is what I have.
line = input('Message? ')
print(line[0]+line[3::3].strip())
To join things with spaces, use join(). Consider the following:
>>> line = '0123456789'
>>> ' '.join(line[::3])
'0 3 6 9'
Since you're using Python 3, you can use * to unpack the line and send each element as an argument to print(), which uses a space as the default separator between arguments. You don't need to separate line[0] from the rest - you can include it in the slice ([0::3]), or it'll be used by default ([::3]). Also, there's no need to use strip(), as the newline character that you send with Enter is not included in the string when you use input().
print(*input('Message? ')[::3])
In C++, \n is used, but what do I use in Python?
I don't want to have to use:
print (" ").
This doesn't seem very elegant.
Any help will be greatly appreciated!
Here's a short answer
x=' '
This will print one white space
print(x)
This will print 10 white spaces
print(10*x)
Print 10 whites spaces between Hello and World
print(f"Hello{x*10}World")
If you need to separate certain elements with spaces you could do something like
print "hello", "there"
Notice the comma between "hello" and "there".
If you want to print a new line (i.e. \n) you could just use print without any arguments.
A lone print will output a newline.
print
In 3.x print is a function, therefore:
print()
print("hello" + ' '*50 + "world")
Any of the following will work:
print 'Hello\nWorld'
print 'Hello'
print 'World'
Additionally, if you want to print a blank line (not make a new line), print or print() will work.
First and foremost, for newlines, the simplest thing to do is have separate print statements, like this:
print("Hello")
print("World.")
#the parentheses allow it to work in Python 2, or 3.
To have a line break, and still only one print statement, simply use the "\n" within, as follows:
print("Hello\nWorld.")
Below, I explain spaces, instead of line breaks...
I see allot of people here using the + notation, which personally, I find ugly.
Example of what I find ugly:
x=' ';
print("Hello"+10*x+"world");
The example above is currently, as I type this the top up-voted answer. The programmer is obviously coming into Python from PHP as the ";" syntax at the end of every line, well simple isn't needed. The only reason it doesn't through an error in Python is because semicolons CAN be used in Python, really should only be used when you are trying to place two lines on one, for aesthetic reasons. You shouldn't place these at the end of every line in Python, as it only increases file-size.
Personally, I prefer to use %s notation. In Python 2.7, which I prefer, you don't need the parentheses, "(" and ")". However, you should include them anyways, so your script won't through errors, in Python 3.x, and will run in either.
Let's say you wanted your space to be 8 spaces,
So what I would do would be the following in Python > 3.x
print("Hello", "World.", sep=' '*8, end="\n")
# you don't need to specify end, if you don't want to, but I wanted you to know it was also an option
#if you wanted to have an 8 space prefix, and did not wish to use tabs for some reason, you could do the following.
print("%sHello World." % (' '*8))
The above method will work in Python 2.x as well, but you cannot add the "sep" and "end" arguments, those have to be done manually in Python < 3.
Therefore, to have an 8 space prefix, with a 4 space separator, the syntax which would work in Python 2, or 3 would be:
print("%sHello%sWorld." % (' '*8, ' '*4))
I hope this helps.
P.S. You also could do the following.
>>> prefix=' '*8
>>> sep=' '*2
>>> print("%sHello%sWorld." % (prefix, sep))
Hello World.
rjust() and ljust()
test_string = "HelloWorld"
test_string.rjust(20)
' HelloWorld'
test_string.ljust(20)
'HelloWorld '
Space char is hexadecimal 0x20, decimal 32 and octal \040.
>>> SPACE = 0x20
>>> a = chr(SPACE)
>>> type(a)
<class 'str'>
>>> print(f"'{a}'")
' '
Tryprint
Example:
print "Hello World!"
print
print "Hi!"
Hope this works!:)
this is how to print whitespaces in python.
import string
string.whitespace
'\t\n\x0b\x0c\r '
i.e .
print "hello world"
print "Hello%sworld"%' '
print "hello", "world"
print "Hello "+"world
Sometimes, pprint() in pprint module works wonder, especially for dict variables.
simply assign a variable to () or " ", then when needed type
print(x, x, x, Hello World, x)
or something like that.
Hope this is a little less complicated:)
To print any amount of lines between printed text use:
print("Hello" + '\n' *insert number of whitespace lines+ "World!")
'\n' can be used to make whitespace, multiplied, it will make multiple whitespace lines.
In Python2 there's this.
def Space(j):
i = 0
while i<=j:
print " ",
i+=1
And to use it, the syntax would be:
Space(4);print("Hello world")
I haven't converted it to Python3 yet.
A lot of users gave you answers, but you haven't marked any as an answer.
You add an empty line with print().
You can force a new line inside your string with '\n' like in print('This is one line\nAnd this is another'), therefore you can print 10 empty lines with print('\n'*10)
You can add 50 spaces inside a sting by replicating a one-space string 50 times, you can do that with multiplication 'Before' + ' '*50 + 'after 50 spaces!'
You can pad strings to the left or right, with spaces or a specific character, for that you can use .ljust() or .rjust() for example, you can have 'Hi' and 'Carmen' on new lines, padded with spaces to the left and justified to the right with 'Hi'.rjust(10) + '\n' + 'Carmen'.rjust(10)
I believe these should answer your question.