-1

I am having difficulty removing white space in front of the character. I am trying to parse the sample string object below:

Mary Whitten: {laptop: 100, tv : 5, xbox: 50, }, James Doe: {laptop: 30, tv: 3,  xbox: 5,}, Jesus Navas: {laptop: 25, tv: 3, xbox: 5},Matt Mart:{laptop:10, xbox: 10}

i also used .split('},') while parsing the above string. The keys that I got:

d=['Mary Whitten', ' James Doe', ' Jesus Navas', 'Matt Mart']

there are some white spaces in front of ' James Doe' and ' Jesus Navas' which I am trying to avoid because keys are sensitive to white spaces i.e d['James Doe'] is not same as [' James Doe'] because of the white space in the key. How would I avoid it? Also, I wanted to make the list items case insensitive like:

d=(items.lowercase() for items in d)
user3399326
  • 863
  • 4
  • 13
  • 24
  • You can use `strip`. [trimming a string](http://stackoverflow.com/a/6039813/3336968) – fredtantini Mar 25 '14 at 14:59
  • Have you tried parsing it as a [`json`](http://docs.python.org/2/library/json.html) string? – tobias_k Mar 25 '14 at 15:01
  • The answers below are correct, but I cannot help wondering where you are getting this string from. It seems like it wants to be json but isn't quite. Are you able to change the way the string is produced to make it easier to parse? – Steven Rumbalski Mar 25 '14 at 15:21
  • yes i get what you are trying to say. i haven't tried using json yet. the only problem i am having is i am unable to change the white space in front of ' James Doe' key string. for instance dict={' James Doe':{laptop:10}} – user3399326 Mar 25 '14 at 16:08

2 Answers2

2

Look at strip(), lstrip() and rstrip(). Docs here.

For example:

>>> 'Mary Whitten '.rstrip()
'Mary Whitten'
>>> ' James Doe'.lstrip()
'James Doe'
>>> ' Jesus Navas '.strip()
'Jesus Navas'

If you only want certain characters stripped (such as only whitespace), you can feed the .*strip methods a character or iterable of characters, such as .strip(" ") or '.rstrip("\?\.\!\n").

For your purpose, it looks like

d = (items.lower().strip() for items in d)
wflynny
  • 18,065
  • 5
  • 46
  • 67
0

You can simply do that as follows:

string.strip()

Running this script on " Hello " would give "Hello"

For your code, you would do it as follows:

d = [item.strip() for item in d]

>>> d = (item.lower().strip() for item in d)
>>> print d
['mary whitten', 'james doe', 'jesus navas', 'matt mart']
sshashank124
  • 31,495
  • 9
  • 67
  • 76