1

I am extracting data from json file using python. Every thing is working however in the case when the data(value) of key is received from multiline input window component of form where the user press enter after every word. I get problem. So when the input is like the following in multiline input field

apple
orange
banana

When I print the value of the key with python using the following code. It print the data as it is like including enters(line breaks). I am looking for input without line break in my extraction

apple orange banana

The code I am using to print is

    if item['fruit'][0]:
        if 'Other' in item['fruit'][0]:
            print (item['fruit'][0]['Other'], end="| ")
        else:
            print ('NULL', end="| ")
    else:
          print('NULL', end="| ")
Nimko
  • 139
  • 1
  • 8
  • 1
    Why don't you just replace all `\n` newline characters with spaces, using the built-in `str.replace` method? – PM 2Ring Feb 09 '16 at 11:32
  • I guess thats the answer but I am new can you change this line to do that for me. print (item['fruit'][0]['Other'], end="| ") – Nimko Feb 09 '16 at 11:34
  • It's hard to give exact advice without seeing your data, but try this: `print(item['fruit'][0]['Other'].replace('\n', ' '), end="| ")`. If that doesn't work, please paste the output of `print(repr(item['fruit'][0]['Other']))` into your question. – PM 2Ring Feb 09 '16 at 11:39
  • Possible duplicate of [Remove all line breaks from a long string of text](http://stackoverflow.com/questions/16566268/remove-all-line-breaks-from-a-long-string-of-text) – PM 2Ring Feb 09 '16 at 11:44
  • This is the better one because the above one only replace the last \n "''.join(string.splitlines()) – Nimko Feb 09 '16 at 12:40
  • Ok. [`.replace(old, new)`](https://docs.python.org/3/library/stdtypes.html#str.replace) does actually replace all occurrences of `old` with `new`. But it appears that your data has more than just a simple `\n` separating the lines, and `.splitlines()` takes care of that for you. I suspected that you might have other characters in there apart from `\n`, which is why I asked you to post the `repr()` of your data so I could see exactly what was there. But it's great that you've solved your problem. – PM 2Ring Feb 09 '16 at 12:51

0 Answers0