How to print without newline in Python? This is a question that has troubled many newbie programmers in Python. It’s because you may want to print multiple values on the same line. As Python prints every output on a different line by default, you might get confused.
The Problem
Printing the output is probably the most common command in any programming language and among the first commands that you lean. Similarly, it is among the first commands you will learn in Python.
However, unlike other programming languages that print several outputs in the same line without a new line command, Python by default prints every output on a different line.
For Example
print("Good Morning!")
print("What a wonderful day!")
Output
Good Morning!
What a wonderful day!
To print without a newline, all you have to do is add an additional argument at the end of your print statement. This argument is called end. In this post, we will learn more about this and other methods.
Python Print Without Newline: The Methods
- Using «end» argument in the print statement (Python 3.X)
- Using «sys» library (Python 3.X)
- Using «comma» at the end of your print statement (Python 2.X)
1. Using «end» Argument in the print statement (Python 3.X)
In Python 3, print() is a function that prints output on different lines, every time you use the function. However, you can avoid this by introducing the argument end and assigning an empty string to it. This will prevent the next output from being printed in a new line.
# use the argument "end" to specify the end of line string
print("Good Morning!", end = '')
print("What a wonderful day!")
Output:
Good Morning!What a wonderful day!
2. Using «sys» Library (Python 3.X) to Print Without Newline
#Import the inbuilt sys library
import sys
#First Line of output
sys.stdout.write("Hey! Welcome to the STechies.")
#Second Line of output
sys.stdout.write("We have the best python tutorial")
Output:
Hey! Welcome to the STechies.We have the best python tutorial
Code Explanation:
The sys module in Python contains many functions and variables to work on the runtime environment. The information about functions, constants and methods of the Python interpreter is present in this module.
The sys.stdout is a file object that is used for displaying the output of a print statement. The sys.stdout.write() method does not add a newline at the end of a string to be displayed.
In the code, you can see that both strings are printed on the same line without any spaces in between.
Note: The output of both the example above will be in one line without adding space in between the strings.
Python Print Without Newline: Adding a Space at the End
Now if you want to insert a space in your output, you have to use a space at the end of your first print function.
Input
# use the argument "end" to specify the end of line string and print with space
print("Good Morning! ", end = '')
print("What a wonderful day!")
Output
Good Morning! What a wonderful day!
Printing a «List» With «for» Loop Without New Line
Code Example:
# Python program to print list without new line character
# Declare a List
listfruits = ['Apple', 'Banana', 'Orange', 'Mango']
# Print list using for Loop
for fruit in listfruits:
print(fruit, end='')
Output:
AppleBananaOrangeMango
Explanation:
In the program written above, the elements of a list are stored in a variable called listfruits. A for loop is executed to iterate over the elements and print them out one by one. You can see that an end argument is passed along with the print statement. This avoids the strings to be printed on different lines.
You can see that the elements of the list are printed together on the same line without any spaces.
Printing with a Space between List Items
Code Example:
# Python program to print list without new line character
# Declare a List
listfruits = ['Apple', 'Banana', 'Orange', 'Mango']
# Print list using for Loop
for fruit in listfruits:
print(fruit, end=' ')
Output:
Apple Banana Orange Mango
Explanation:
Here, a for loop iterated over list items to print them out on the same line using the print statement. This is achieved by passing the end argument that contains the value of an empty string. There is a space between the single quotes, as observed in the code. This creates a space between the list elements when printed out on a single line.
Printing Without A Newline In Python 2.X
To print without newline in Python 2.X, you have to use a comma where your print statement ends.
Unlike Python 3.X, Python 2.X does not have the ‘end’ argument.
3. Using «comma» to Terminate Print Statement
In order to print in the same line in Python 2.X, all you have to do is terminate your print statement with a comma.
In the example below, the print statement is terminated with a comma.
Input
# print without a newline but with space
# terminate print statement with a comma
print ("Good Morning!"),
print ("What a wonderful day!")
Output
Good Morning! What a wonderful day!
A space character is used to separate the two lines.
Python Print Without Newline Video Tutorial
Conclusion
With most other programming languages requiring the position of a new line being mentioned in the program, many first time users may find printing with Python a little inconvenient. However, it is actually time-saving as it automatically detects a new line in the output with every print function or statement.
Whenever you need an output printed in the same line, all you need to do is to terminate your print function with the argument ‘end’ in Python3 or introduce a comma in Python 2.This simple addition will help you get rid of your new line woes!
На чтение 4 мин Просмотров 9к. Опубликовано 14.03.2021
Сегодня я рассмотрю различные способы печати значений без возврата символа новой строки или каретки. Это очень полезная статья!
Содержание
- Введение
- Печать без новой строки
- Печать без новой строки в Python 2.X
- Использование stdout.write
- Заключение
Введение
Функция print в Python добавляет новую строку к выходным данным при отображении в терминале. Если вы не хотите, чтобы ваше сообщение отображалось с новыми строками или пробелами, то как вы можете изменить поведение функции print?
Этого можно легко достичь, изменив значения по умолчанию параметров sep и end функции print.
Печать без новой строки
До версии Python 2.x, print было зарезервированным ключевым словом, которое действует как специальный оператор. Начиная с Python версии 3.x, команда print превратилась в функцию.
Эта версия print способна принимать следующие аргументы:
Значения (value1, value2), упомянутые выше, могут быть любой строкой или любым из типов данных, таких как list, float, string и так далее. Другие аргументы включают разделитель sep, используемый для разделения значений, заданных в качестве аргументов, в то время как аргумент end по умолчанию является символом новой строки «n». Именно по этой причине при каждом вызове функции print курсор перемещается на следующую строку.
В Python 3.x самый простой способ печати без новой строки — это установить аргумент end в виде пустой строки, то есть » «. Теперь, попробуйте выполнить следующий фрагмент кода в интерпретаторе Python:
print("I am a sentence", "I am also a sentence")
Интерпретатор выдаст следующее:
I am a sentence I am also a sentence
Мы печатаем две строки, поэтому Python будет использовать значение «sep», пустое пространство по умолчанию, чтобы напечатать их вместе. Python также добавляет символ новой строки в конце, поэтому приглашение интерпретатора переходит в конечную строку.
Теперь измените предыдущее утверждение так, чтобы оно выглядело следующим образом:
print("I am a sentence", "I am also a sentence", sep="; ", end="")
Выполнив его в интерпретаторе, вы получите результат, напоминающий:
I am a sentence; I am also a sentence
Здесь произошло следующее: разделитель между двумя строками теперь также включает точку с запятой. Приглашение интерпретатора также появляется в той же строке, потому что мы удалили автоматически добавляемый символ новой строки.
Печать без новой строки в Python 2.X
Для более ранних версий Python (старше 3, но больше 2.6), вы можете импортировать print_function из модуля __future__. Это переопределит существующее ключевое слово print с помощью функции print, как показано ниже:
from __future__ import print_function print("I am a sentence", "I am also a sentence", sep="; ", end="")
Вывод программы:
I am a sentence; I am also a sentence
Вот как вы можете использовать функцию print от Python версии 3 в Python 2.x.
Использование stdout.write
Модуль sys имеет встроенные функции для записи непосредственно в файл или в TTY. Эта функция доступна для версий Python 2.x и 3.x. Мы можем использовать метод write объекта stdout модуля sys для печати на консоли следующим образом:
import sys sys.stdout.write("I am a line")
Вывод программы:
Хотя это дает результат того, чего мы пытаемся достичь, существует довольно много различий между функцией write и функцией print. Функция print может печатать несколько значений одновременно, может принимать нестроковые значения и более дружелюбна к разработчикам.
Заключение
В этой статье я рассмотрел различные способы печати значений без возврата символа новой строки/каретки. Эта стратегия может оказаться весьма полезной при печати элементов в выходных данных алгоритмов, таких как двоичное дерево или печать содержимого списка рядом друг с другом.
На этом всё!
Introduction
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="")
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!
This will also yield:
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:
I am a line>>>
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.
Problem Formulation
Python’s print()
function allows an arbitrary number of comma-separated values and prints them to the shell, separated by a single empty space character ‘ ‘.
The following example shows how you pass four string values as arguments into the print()
function:
>>> print('learn', 'python', 'with', 'finxter') learn python with finxter
The resulting shell output has an added empty space character ' '
to separate those four values.
How to print without the extra space?
Solution With Separator Argument
To print multiple values or variables without the default single space character in between, use the print()
function with the optional separator keyword argument sep
and set it to the empty string ''
. For example, the statement print('hello', 'world', sep='')
prints helloworld
without the added empty space separator character.
>>> print('learn', 'python', 'with', 'finxter', sep='') learnpythonwithfinxter
Per default, the separator keyword argument is set to the empty space sep=' '
. You can also set it to any other string such as sep='-foo-'
to obtain the following code:
>>> print('learn', 'python', 'with', 'finxter', sep='-foo-') learn-foo-python-foo-with-foo-finxter
To learn more about the print function and its not very well-known arguments, feel free to watch my explainer video here:
Python Print Function [And Its SECRET Separator & End Arguments]
Solution Without Separator Argument
To print multiple values or variables without the default single space character in between without explicitly overwriting the default separator argument, merge the multiple values using string concatenation before printing a single string. For example, the statement print('hello' + 'world')
prints helloworld
without the added empty space separator character.
>>> print('learn' + 'python' + 'with' + 'finxter') learnpythonwithfinxter
While this solution doesn’t need a separator argument and a comma-separated argument list, it does need the plus operator + to concatenate two strings repeatedly until only one string is left. This can be tedious to write—and it may not be the most efficient solution due to the repeated creation of a new string based on two old string objects.
Solution to Print List of Strings Without Empty Space
To print a list of strings without an empty space as a separator, you have two options:
- Use the separator argument
sep=''
like so:print(*str_list, sep='')
- Merge the list into a single string using
string.join()
like so:print(''.join(str_list))
You can find the first way using unpacking here:
>>> str_list = ['learn', 'python', 'with', 'finxter'] >>> print(*str_list, sep='') learnpythonwithfinxter
And the second way using string.join()
here:
>>> str_list = ['learn', 'python', 'with', 'finxter'] >>> print(''.join(str_list)) learnpythonwithfinxter
To learn more about this, feel free to read my tutorial on the string.join()
method.
Python String Methods [Ultimate Guide]
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
Join the free webinar now!
💡 Recommended Tutorial: How to Print Spaces in Python?
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.
I’m not gonna lie. There are multiple ways you can trim a string in Python.
But… the truth is, you don’t need to know every one of them.
In this article, you’ll see only the most important techniques, such as stripping leading and trailing spaces (as well as the ones inside the string). You’ll also learn how to remove tabs, newlines, carriage return (CRLF), and other characters. And we’ll be using nothing more than native methods and regex—no external libraries required!
By the end of this article, you’ll have mastered:
-
How to trim a string
-
by stripping leading whitespace from the beginning
-
by stripping trailing whitespace from the end
-
by removing spaces the start and end of a string
-
-
How trim newlines
-
How trim carriage return (CRLF)
-
How trim tabs
-
How to trim a combination of characters from a string
-
How to remove multiple spaces inside a string
-
by removing only duplicates
-
by removing all spaces
-
-
How to strip a list of strings
- How to strip an (Numpy) array of strings
How to Trim Characters From a String
Trimming a string means deleting certain chars from the start, the end, or both sides of a string. Removing unwanted chars makes it easier to compare strings and can prevent hard to debug issues.
You can remove any kind o character, but usually what we’re interested in is deleting blank spaces, new lines, carriage return (CRLF), tabs and other special symbols.
In this section, we’re going to see how to remove leading or trailing spaces, blank spaces, newline character, carriage return (CRLF), and tabs.
Stripping Leading Whitespace From Beginning of a String
The str
class has a very convenient method to trim leading spaces named str.lstrip
, a shorthand for «left-strip», since it trims a string from the left-hand side. You can think of it as a left trim.
>>> ' hello '.lstrip()
'hello '
When calling str.lstrip
with no arguments, it removes all whitespaces from left to right. But if all you want is to strip the first char, then there are two ways of doing this. The first one assumes that there will always be at least one whitespace in the beginning of the string. If that’s the case, then you can just slice it.
>>> s = ' hello'
>>> s = s[1:]
>>> s
' hello'
If there’s no guarantee of that, we’ll need to check first if the string starts with space.
>>> def strip_first(s: str, ch: str = ' ') -> str:
if s and s[0] == ch:
return s[1:]
return s
>>> strip_first('hello')
'hello'
>>> strip_first(' hello')
' hello'
Stripping Trailing Whitespace From End of a String
The way to remove trailing spaces from the end of the string is to use str.rstrip
.
This method expects a list of chars and trims the string from the right. It removes all chars that match one of those you passed, and stop as soon as it cannot match anymore. By default, str.rstrip()
removes blanks if you don’t pass anything to it. You can think of it as a right trim.
>>> ' hello '.rstrip()
' hello'
>>> '***hello***'.rstrip('*')
'***hello'
Sometimes you might want to trim only the last character of a string. And we can use the same logic from the previous example. Check if the last char is a space, and use slice to remove it.
>>> def strip_last(s: str, ch: str = ' ') -> str:
if s and s[-1] == ch:
return s[:-1]
return s
>>> strip_last('hello')
'hello'
>>> strip_last('hello ')
'hello'
>>> strip_last('')
''
Removing Spaces From From Start and End of a String
If all you want is to remove whitespaces from start and end of string, str.strip
will serve you better.
This method trims both sides of the string. And just like str.lstrip
and str.rstrip
, if you can pass any combination of chars as argument, it removes them from both ends.
⚠️ WARNING ⚠️: A common misconception is to think that there’s a trim() function in Python.
# by default, strip removes whitespaces
>>> ' hello '.strip()
'hello'
# but you can also strip other character
>>> '***hello***'.strip('*')
'hello'
How to Trim Newlines
We’ve seen how str.strip
can remove blank spaces from both sides of a string. I’ve also mentioned that this method takes a chars argument that you can use pass a combination of character you want to trim.
To trim line breaks, you can pass n
and it will strip all newlines from both sides of the string.
>>> s = """
...
...
... hello
...
...
... """
>>> s
'nnn hellonnn'
>>> s.strip('n')
' hello'
How to Trim Carriage Return (CRLF)
The Carriage Return (CR), and Line Feed (LF) are nothing more than a newline character. They are represented by the concatenation of r
and n
forming rn
. This is how Microsoft Windows, Symbian OS and other non-Unix operating systems represent a new line [source].
Removing them from a string is the same as removing the single newline. You feed str.strip
with rn
and method does its job!
>>> s = " hello worldrnrn"
>>> print(s)
hello world
>>> s.strip('rn')
' hello world'
How to Trim Tabs
If you are following this guide from the beginning you might already know how to do this. Trimming tabs from a string in Python is the same as other characters, you use str.strip
and pass the ‘t’ string to it.
>>> s = "ttt hello world t"
>>> s
'ttt hello world t'
>>> print(s)
hello world
>>> s.strip('t')
' hello world '
And that’s it!
How to Trim a Combination of Characters From a String
As I mentioned before, str.strip
takes as argument a string, not just a single char. This sequence of chars is a combination of all chars you want to remove from the beginning and end of your string.
>>> s = " ns hello world n s"
>>> s
' ns hello world n s'
>>> print(s)
s hello world
s
>>> s.strip('n s')
'hello world'
How to Remove Multiple Spaces Inside a String
Sometimes you want to do more than trimming, let’s say you want to remove chars inside the string. There are two ways of doing this: one is to remove only the duplicates; the other is to remove all extra spaces.
Removing Only Duplicates
To remove only the duplicated characters, you can use the regex module re
>>> import re
>>> s = " Python is really a great language. "
>>> re.sub("s+" , " ", s)
' Python is really a great language. '
This method gets rid of all consecutive spaces. What if you want to do not only that, but also trim the string by removing the leading and trailing blanks?
One way is to split the string and then joining then like so:
>>> s = " Python is really a great language. "
>>> " ".join(s.split())
'Python is really a great language.'
>>> # This is the same as using regex then stripping the whitespaces
>>> re.sub("s+" , " ", s).strip()
'Python is really a great language.'
Removing All Spaces
Now, if you want to strip all whitespace in your string, either use regex or call the str.replace
method.
Using re
(regex module)
>>> import re
>>> s = " Python is really a great language. "
>>> re.sub("s+" , "", s)
'Pythonisreallyagreatlanguage.'
Using replace
>>> s = " Python is really a great language. "
>>> s.replace(' ', '')
'Pythonisreallyagreatlanguage.'
How to Strip a List of Strings
Trimming a list of strings is almost the same as trimming an individual one. The only difference is that you have to iterate over the list, and call str.strip
method on each one. You do so by using a list comprehension, for example, to return a new list with all strings trimmed.
>>> lst = ["string1n", "string2n", "string3n"]
>>> [s.strip('n') for s in lst]
['string1', 'string2', 'string3']
How to Strip an (Numpy) Array of Strings
It’s very common to use Numpy for data science tasks due to its performance and ease to use.
If you have a array of strings and want to trim each one of them, Numpy comes with an efficient vectorized implementation of strip
.
In fact, it also has .lstrip
, .rstrip
, .replace
, and many other string operations.
The vectorized versions work slightly differently, they are not a method but a function in the numpy.char
module. So you must pass the array and the list of chars you want to trim.
>>> import numpy as np
>>> arr = np.array([' helloworld ', ' hello'])
array([' helloworld ', ' hello'], dtype='<U7')
>>> np.char.strip(arr, ' ')
array(['helloworld', 'hello'], dtype='<U7')
Conclusion
In this post, you learned several ways of trimming a string in Python, including array of strings. Python allows us to strip leading and trailing characters easily. And if instead of removing the extra chars on each side you want to remove the ones internally, you can count on the regex module. I hope you’ve found this article helpful and see you next time!
References:
stackoverflow.com/questions/761804/how-do-i..
stackoverflow.com/questions/8270092/remove-..
stackoverflow.com/questions/1546226/is-ther..
Other posts you may like:
-
How to Choose Between isdigit(), isdecimal() and isnumeric() in Python
-
How to Compare Two Strings in Python (in 8 Easy Ways)
-
Pylint: How to fix «c0209: formatting a regular string which could be a f-string (consider-using-f-string)»
-
How to Implement a Random String Generator With Python
-
How to Check If a String Is a Valid URL in Python
-
Python F-String: 73 Examples to Help You Master It
See you next time!
This post was originally published at https://miguendes.me
Remove space in python string / strip space in python string : In this Tutorial we will learn how to remove or strip leading , trailing and duplicate spaces in python with lstrip() , rstrip() and strip() Function with an example for each . lstrip() and rstrip() function trims the left and right space respectively. strip() function trims all the white space.
objective:
- Remove (strip) space at the start of the string in Python – trim leading space
- Remove (strip) space at the end of the string in Python – trim trailing space
- Remove (strip) white spaces from start and end of the string – trim space.
- Remove all the spaces in python
- Remove Duplicate Spaces in Python
- Trim space in python using regular expressions.
Let’s see the example on how to Remove space in python string / strip space in python string one by one.
Remove Space at the start of the string in Python (Strip leading space in python):
## Remove the Starting Spaces in Python string1=" This is Test String to strip leading space" print (string1) print (string1.lstrip())
lstrip() function in the above example strips the leading space so the output will be
‘ This is Test String to strip leading space’
‘This is Test String to strip leading space’
Remove Space at the end of the string in Python (Strip trailing space in python):
## Remove the Trailing or End Spaces in Python string2="This is Test String to strip trailing space " print (string2) print (string2.rstrip())
rstrip() function in the above example strips the trailing space so the output will be
‘This is Test String to strip trailing space ‘
‘This is Test String to strip trailing space’
Remove Space at the Start and end of the string in Python (Strip trailing and trailing space in python):
## Remove the whiteSpaces from Beginning and end of the string in Python string3=" This is Test String to strip leading and trailing space " print (string3) print (string3.strip())
strip() function in the above example strips, both leading and trailing space so the output will be
‘ This is Test String to strip leading and trailing space ‘
‘This is Test String to test leading and trailing space’
Remove or strip all the spaces in python:
## Remove all the spaces in python string4=" This is Test String to test all the spaces " print (string4) print (string4.replace(" ", ""))
The above example removes all the spaces in python. So the output will be
‘ This is Test String to test all the spaces ‘
‘ThisisTestStringtotestallthespaces’
Remove or strip the duplicated space in python:
# Remove the duplicated space in python import re string4=" This is Test String to test duplicate spaces " print (string4) print (re.sub(' +', ' ',string4))
- We will be using regular expression to remove the unnecessary duplicate spaces in python.
- sub() function: re.sub() function takes the string4 argument and replaces one or more space with single space as shown above so the output will be.
‘ This is Test String to test duplicate spaces ‘
‘ This is Test String to test duplicate spaces ‘
Using Regular Expression to trim spaces:
re.sub() function takes the string1 argument and apply regular expression to trim the white spaces as shown below
string1 = " This is to test space " print('Remove all space:',re.sub(r"s+", "", string1), sep='') # trims all white spaces print('Remove leading space:', re.sub(r"^s+", "", string1), sep='') # trims left space print('Remove trailing spaces:', re.sub(r"s+$", "", string1), sep='') # trims right space print('Remove leading and trailing spaces:', re.sub(r"^s+|s+$", "", string1), sep='') # trims both
so the resultant output will be
Remove all space:’Thisistotestspace’
Remove leading space:’This is to test space ‘
Remove trailing spaces:’ This is to test space’
Remove leading and trailing spaces:’This is to test space’