- What is the whitespace constant in Python?
- The string module
- The whitespace constant
- Syntax
- Example 1
- Explanation
- Example 2
- Explanation
- Print Values Without Spaces in Between in Python
- Use the String Formatting With the Modulo % Sign in Python
- Use the String Formatting With the str.format() Function in Python
- Use String Concatenation in Python
- Use the f-string for String Formatting in Python
- Use the sep Parameter of the print Statement in Python
- Related Article — Python Print
- Python: How to Print without Newline or Space
- Printing without a Newline
- Printing Without a Newline in Python 2.X
- Free eBook: Git Essentials
- Using stdout.write()
- Conclusion
- Folyamatosan induló kurzusaink
- Tanulj online
- Interaktív feladatok
- Előképzettség nélkül
- Örökös hozzáférés
- Tapasztalt mentorok
- Pénzvisszafizetési garancia
What is the whitespace constant in Python?
Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.
The string module
The string module in Python is a collection of different constants.
The whitespace constant
The whitespace constant in the string module contains the characters that are considered whitespace.
The value of the constant is as follows:
Syntax
Since whitespace is a constant, we can access it via the string module.
Let’s look at two code examples that use the whitespace constant.
Example 1
import stringwhitespace_output = string.whitespaceprint("Hello")print(whitespace_output)print("World")
Explanation
- Line 1: We import the string module.
- Line 3: We store the output of string.whitespace in the whitespace_output variable.
- Line 5: We print the whitespace_output variable.
Example 2
import stringdef contains_whitespace(str_input):for i in str_input:if i in string.whitespace:return Truereturn Falsestr_to_check_1 = "abjiaosfdgfRFDFD"print("Does %s contain any whitespace? %s" % (str_to_check_1, contains_whitespace(str_to_check_1)))str_to_check_2 = "abji232daosfdgfR. FDFD"print("Does %s contain any whitespace? %s" % (str_to_check_2, contains_whitespace(str_to_check_2)))
Explanation
- Line 1: We import the string module.
- Lines 3–9: We define a function called contains_whitespace that accepts a string as its parameter. It also checks whether this string contains any whitespace characters or not.
- Line 11: We define a string called str_to_check_1 with no whitespace characters.
- Line 12: We invoke the contains_whitespace function by passing str_to_check_1 as the parameter.
- Line 14: We define a string called str_to_check_2 containing whitespace characters.
- Line 15: The contains_whitespace function is invoked passing str_to_check_2 as the parameter.
Print Values Without Spaces in Between in Python
- Use the String Formatting With the Modulo % Sign in Python
- Use the String Formatting With the str.format() Function in Python
- Use String Concatenation in Python
- Use the f-string for String Formatting in Python
- Use the sep Parameter of the print Statement in Python
When we generally use the print statement, we sometimes use a comma ( , ) as a separator, which sometimes leads to unnecessary spaces between values. Fortunately, you can utilize some alternatives in Python that help you handle these spacing problems.
In this guide, we’ll teach you how to use the different methods to print without spaces between values in Python.
We will take a simple code for all the methods, which takes up a print statement and contains several arguments separated by commas. For example, the following program below uses the comma operator to print the values.
x = 10 print ('The number of mangoes I have are "', x, '"')
The number of mangoes I have are " 10 "
We should note that there are unnecessary spaces between the number 10 and the double quotes surrounding it. The aim is to prevent or remove this excessive or unnecessary spacing.
Use the String Formatting With the Modulo % Sign in Python
String formatting gives more customization options to the users to go with the classic print statement. The % sign is also known as an interpolation or a string formatting operator.
String formatting can be implemented in two ways, and using the % sign is one of those options.
The % sign, followed by a letter that represents the conversion type, works as a placeholder for the variable. The code below uses the % sign to print without spaces between values in Python.
x = 10 print ('The number of mangoes I have are "%d"' %x )
The number of mangoes I have are "10"
Use the String Formatting With the str.format() Function in Python
When using the string formatting, braces <> are used to mark the spot in the statement where the variable would be substituted.
The str.format() has been introduced in Python 3 and is available to use in the latest versions of Python. This function is utilized for the efficient handling of complex string formatting.
The following code uses the str.format() function to print without spaces between values in Python.
x = 10 print ('The number of mangoes I have are "<>"'.format(x) )
The number of mangoes I have are "10"
It is recommended to use the format() function instead of the old % operator in the newer versions of Python.
Use String Concatenation in Python
The + operator, also known as the string concatenation operator, can be used in this case to prevent unnecessary spacing between the values. It’s a direct alternative to comma separation and can be used along with the print statement.
Here is an example code that shows the use of string concatenation in the print statement.
x = 10 print ('The number of mangoes I have are "' + str(x) + '"')
The number of mangoes I have are "10"
Use the f-string for String Formatting in Python
Python 3.6 introduced the f-string , which is another method of achieving string formatting; however, it has the edge over the two other processes for string formatting mentioned above because it’s comparatively faster than its other two peers.
The following code uses the fstring formatting to print without spaces between values in Python.
x = 10 print (f'The number of mangoes I have are "x>"')
The number of mangoes I have are "10"
Use the sep Parameter of the print Statement in Python
You can modify the spacing between the arguments of the print statement by using the sep parameter. The sep parameter can only be found and used in Python 3 and later versions. It can also be utilized for the formatting of the output strings.
The following code uses the sep parameter to print without spaces between values in Python.
x = 10 print ('The number of mangoes I have are "', x, '"', sep='')
The number of mangoes I have are "10"
Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.
Related Article — Python Print
Python: How to Print without Newline or Space
The print() function in Python appends a newline to the output when displayed on the tty (teletypewriter A.K.A the terminal). When you don’t want your message displayed with newlines or with spaces, how can you change the behavior of print() ?
This can easily be achieved by altering the default values of the sep and end parameters of the print() function.
Printing without a Newline
Until Python version 2.x, print was a reserved keyword that acts as a special statement. Since Python version 3.x, the print command has evolved into a function.
This version of print() is capable of taking the following arguments:
The values ( value1 , value2 ) mentioned above can be any string or any of the data types like list, float, string, etc. The other arguments include a separator ( sep ) used to divide the values given as arguments whereas the argument end is the \n newline character by default. This is the reason why whenever the print() function is called, the cursor slides to the next line.
In Python 3.x, the most straightforward way to print without a newline is to set the end argument as an empty string i.e. » . For example, try executing the following snippet in your Python interpreter:
print("I am a sentence", "I am also a sentence")
The interpreter would output the following:
I am a sentence I am also a sentence >>>
We are printing two strings, so Python will use the value of sep , a blank space by default, to print them together. Python also adds a newline character at the end, so the interpreter prompt goes to the end line.
Now modify the previous statement to look like this:
print("I am a sentence", "I am also a sentence", sep="; ", end="")
Upon executing it in the interpreter, you will get an output resembling:
I am a sentence; I am also a sentence>>>
Two things happened here — the separator between the two strings now also includes a semicolon. The interpreter prompt also appears on the same line because we removed the automatically appended newline character.
Printing Without a Newline in Python 2.X
For earlier versions of Python — less than 3 but greater than 2.6 — you can import print_function from the __future__ module. This will override the existing print keyword with the print() function as shown below:
from __future__ import print_function print("I am a sentence", "I am also a sentence", sep="; ", end="")
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
I am a sentence; I am also a sentence>>>
This is how you can use Python version 3’s print() function in Python 2.x.
Using stdout.write()
The sys module has built-in functions to write directly to the file or the tty. This function is available for Python 2.x and 3.x versions. We can use the write() method of the sys module’s stdout object to print on the console like this:
import sys sys.stdout.write("I am a line")
Let’s execute this and take a look at the output:
Although this gives the output of what we are trying to achieve, there are quite a few differences between the write() function and the print() function. The print() function can print multiple values at a time, can accept non-string values, and is friendlier to developers.
Conclusion
In this article, we have explored the different ways by which values can be printed without a newline character/carriage return. This strategy can come quite handy while printing the elements in the outputs of algorithms such as a binary tree or printing the contents of a list next to each other.
Folyamatosan induló kurzusaink
A CodeBerry megtanít a legmodernebb technológiák használatára, és megadja neked a szükséges tudást és eszközöket ahhoz, hogy fejlesztőként dolgozhass.
Készen állsz a tanulásra? Csatlakozz te is a 160 000 programozást tanuló diákunk csapatához!
Tanulj online
Tanulhatsz otthon, a szünetekben, vagy a kedvenc kávézódban.
Interaktív feladatok
A tudásszintedtől függetlenül több, mint 100 órányi szórakoztató feladatsor vár.
Előképzettség nélkül
Teljesen kezdőként is belevághatsz a kurzusokba, semmilyen programozási ismeretre nincs hozzá szükséged.
Örökös hozzáférés
A kurzusok elvégzése után is bármikor hozzáférhetsz a leckékhez, hogy ismételhess és gyakorolhass, ami a programozás tanulásánál különösen fontos.
Tapasztalt mentorok
A CodeBerry tanárai több év programozói tapasztalattal rendelkező szakemberek, akikre mindig számíthatsz, ha segítségre van szükséged a tanulás folyamán.
Pénzvisszafizetési garancia
Ha nem vagy elégedett a szolgáltatásunkkal, a vásárlástól számított 14 napon belül kérdés nélkül visszaadjuk a pénzed.