Python Forum
Unable to do the proper split using re.sub incase of missing data.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unable to do the proper split using re.sub incase of missing data.
#1
This is my code. I used re to convert more than one spaces into a single space.
Then i split the lines and convert into list format.
When all the fields contains data, then i am getting the expected result.
If any of the field is blank(Designation field in the last record), I am not getting the expected output.

import re
inp1 = '''EMP      GRADE    DESIGNATION         SALARY  
Amy      C        Software Engineer   6K
Rock     A        Admin               8K
Paige    D                            9K'''

temp = re.sub('  +', ' ', inp1)
lista = temp.splitlines ()
print(lista)
Output
['EMP GRADE DESIGNATION SALARY ', 'Amy C Software Enginner 6K', 'Rock A Admin 8K', 'Paige D 9K']

Expected Output: (Additional spaces for Designation field for the last record)
['EMP GRADE DESIGNATION SALARY ', 'Amy C Software Engineer 6K', 'Rock A Admin 8K', 'Paige D <Addtional space here> 9K']
Reply
#2
this looks like fixed width text file. don't use re, use slicing or struct
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Correct/proper way to create save files snakes 0 435 Mar-11-2025, 06:58 PM
Last Post: snakes
  Unable to understand the function string.split() Hudjefa 8 2,262 Sep-16-2024, 04:25 AM
Last Post: Pedroski55
  Pyserial issues with proper loops and binary jttolleson 16 5,567 Nov-02-2023, 08:39 PM
Last Post: deanhystad
  counting lines in split data Skaperen 6 2,744 Oct-07-2022, 07:09 PM
Last Post: Skaperen
  Unable to request image from FORM Data usman 0 1,438 Aug-18-2022, 06:23 PM
Last Post: usman
  Getting proper x,y axis values pyhill00 8 3,695 Jul-29-2022, 06:48 PM
Last Post: pyhill00
  Proper way to do the OR statement? Mark17 5 2,783 Mar-01-2022, 01:54 PM
Last Post: Mark17
  How to read rainfall time series and insert missing data points MadsM 4 3,222 Jan-06-2022, 10:39 AM
Last Post: amdi40
  split txt file data on the first column value shantanu97 2 3,471 Dec-29-2021, 05:03 PM
Last Post: DeaD_EyE
  Pandas: how to split one row of data to multiple rows and columns in Python GerardMoussendo 4 10,017 Feb-22-2021, 06:51 PM
Last Post: eddywinch82

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020