Ask Your Question

Can spaces within variables be eliminated for particular columns using a loop?

asked 2021-11-26 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2022-06-02 23:00:00 +0000

lakamha gravatar image

Yes, spaces within variables for particular columns can be eliminated using a loop in most programming languages. The specific implementation will depend on the programming language being used and the format of the data, but in general, the process involves iterating over the appropriate columns and applying a string manipulation function to remove the spaces.

For example, in Python, if we have a list of strings where each string represents a row in a table, we can use a for loop to split each string into separate columns using a delimiter, and then use the strip() method to remove any leading or trailing spaces from each column:

data = [
  "John  Smith  25   male",
  "Jane  Doe    30   female",
  "Bob   Johnson 40   male"

for i in range(len(data)):
  row = data[i].split()
  row = [column.strip() for column in row]
  data[i] = row



  ['John', 'Smith', '25', 'male'],
  ['Jane', 'Doe', '30', 'female'],
  ['Bob', 'Johnson', '40', 'male']

In this example, we use the split() method to split each row into columns based on spaces (' '), and then use a list comprehension to apply the strip() method to each column to remove any leading or trailing spaces. Finally, we update the original data variable with the cleaned up rows.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer

Question Tools


Asked: 2021-11-26 11:00:00 +0000

Seen: 7 times

Last updated: Jun 02 '22