-1

I'm getting a little stuck here. Say I have a text file that reads:

AAAAAA BBBBBBB

SDSDDSDSD CCCC HEY

And I want Python to convert it into one, continuous string that reads:

AAAAAABBBBBBBSDSDDSDSDCCCCHEY

Only thing is, I need to use the re module. How do I go about doing that? Thanks!

nwb37
  • 1
  • 2
  • I believe you can use [`re.sub`](https://docs.python.org/3/library/re.html#re.sub) to remove all spaces and newlines. Also see: [https://stackoverflow.com/q/5658369/11981207](https://stackoverflow.com/q/5658369/11981207) – Kei Nov 06 '19 at 01:47
  • I had typed the following, but was getting an empty result: `file = open('myfile.txt', 'r').read()` `oneline = re.sub('\n', '', file)` ...but to no avail. If I try to print `oneline`, the only thing that comes up is: `""` Instead, I want the whole string. – nwb37 Nov 06 '19 at 01:48
  • I think you're missing an `r`. re.sub(**r**'\n', '', file) – Kei Nov 06 '19 at 01:57
  • Hmmm, I tried that, too, and whenever I try to print `oneline`, I still just get `"`. :( – nwb37 Nov 06 '19 at 01:59
  • What happens when you print `file`? – Kei Nov 06 '19 at 02:00
  • Only empty space appears! :O – nwb37 Nov 06 '19 at 02:02
  • Try double checking that you have content in `myfile.txt`. Maybe the file hasn't been saved yet and is still blank. – Kei Nov 06 '19 at 02:07

1 Answers1

1

Try stripping all whitespace characters:

inp = """AAAAAA BBBBBBB
SDSDDSDSD CCCC HEY"""
output = re.sub(r'\s+', '', inp)
print(output)

This prints:

AAAAAABBBBBBBSDSDDSDSDCCCCHEY
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • I kind of see what you're saying, but what if `inp` is a really big text file, and you don't want to copy-paste all of the contents of the text file? I tried doing `inp = open('myfile.txt', 'r').read()`, but that wasn't working for me. – nwb37 Nov 06 '19 at 01:56
  • Well if your strategy be to read each line one by one, then you could still use my answer to strip whitespace; the problem is mostly still the same. – Tim Biegeleisen Nov 06 '19 at 01:58
  • If I were to try that, would I have to create a for loop for each individual line? If so, how could I do that? I appreciate you being so patient with me. – nwb37 Nov 06 '19 at 02:01
  • What is the actual output you expect here? – Tim Biegeleisen Nov 06 '19 at 02:04