How do I trim whitespace

+1 vote

Is there a Python function that will trim whitespace (spaces and tabs) from a string?

Example: \t example string\texample string

Aug 20, 2018 in Python by bug_seeker
• 15,520 points
451 views

1 answer to this question.

0 votes

Whitespace on both sides:

s = " \t a string example\t " s = s.strip()

Whitespace on the right side:

s = s.rstrip()

Whitespace on the left side:

s = s.lstrip()

As thedz points out, you can provide an argument to strip arbitrary characters to any of these functions like this:

s = s.strip(' \t\n\r')

This will strip any space, \t, \n, or \r characters from the left-hand side, right-hand side, or both sides of the string.

The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try re.sub:

import re print re.sub('[\s+]', '', s)

That should print out:

astringexample

answered Aug 20, 2018 by Priyaj
• 58,090 points

Related Questions In Python

0 votes
1 answer

How do I trim the leading or trailing zeros from a 1d array in python?

Hey @Akki, you can use the numpy ...READ MORE

answered May 29, 2019 in Python by Wakir
1,466 views
0 votes
1 answer

How do I trim extra zeros from a 2D array in python?

Hey @Laksha, you can try something like ...READ MORE

answered May 29, 2019 in Python by Yamini
2,531 views
0 votes
2 answers

How do I copy a file in python?

copy a file in python  from shutil ...READ MORE

answered Mar 27, 2019 in Python by rajesh
• 1,270 points
968 views
0 votes
1 answer

How do I know what's going to be deleted?

An easy system would be to add ...READ MORE

answered Aug 28, 2018 in Python by anonymous
544 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,067 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
3,488 views
0 votes
1 answer

How do I sort a dictionary by value?

It is not possible to sort a ...READ MORE

answered Jul 30, 2018 in Python by Priyaj
• 58,090 points
551 views
0 votes
1 answer

How do I copy a file in python?

Use the shutil module. copyfile(src, dst) Copy the contents ...READ MORE

answered Jul 31, 2018 in Python by Priyaj
• 58,090 points
740 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP