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,360 points
31 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
• 56,940 points

Related Questions In Python

0 votes
1 answer
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 in Python by Yamini
37 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 in Python by rajesh
• 1,210 points
74 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 27, 2018 in Python by anonymous
40 views
+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 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 348 views
+4 votes
6 answers
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
• 56,940 points
30 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
• 56,940 points
41 views