Python Forum
how do one remove whitespace from a list?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how do one remove whitespace from a list?
#1

I'm trying to make a programme that calculates a mathematical ratio problem. in order to do so i convert the 4 numbers the user enters into list elements, then i perform the operations on them. However, i have a problem with whitespace, how do i remove those in python? Here's my programme:

# !/usr/bin/python
# -*- coding: utf8 -*-
import math


def data_prosesering():
    
    ratio = list(raw_input('ratio syfers: '))

    r1 = float(ratio[0]) * float(ratio[1])
    r2 = float(ratio[2]) * float(ratio[3])

    a = r1/r2

    print math.sqrt(a)


data_prosesering()
First searched and tried to do something like this: d = [x.strip() for x in ratio]
Then however i got stuck so i went searching for solutions again and finally got the idea of trying this:
    pre_ratio = raw_input('ratio syfers: ')
    pre_ratio.split()
    ratio = list(pre_ratio)
    
    print ratio #testing if this works
This however didn't work either. Does anyone know how to solve this problem?

Python version: 2.7
operating system: windows 8
Reply
#2
You can use a regular expression

import re

pre_ratio = re.sub(r'\s', '', pre_ratio)
Reply
#3
list(raw_input().replace(' ', ''))
hee ll o
['h', 'e', 'e', 'l', 'l', 'o']
Reply
#4
Ah yes of course! thanks guys, you solved a lot of struggle for me now :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 442 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  Remove numbers from a list menator01 4 1,328 Nov-13-2022, 01:27 AM
Last Post: menator01
  Remove empty keys in a python list python_student 7 3,028 Jan-12-2022, 10:23 PM
Last Post: python_student
  Remove an item from a list contained in another item in python CompleteNewb 19 5,727 Nov-11-2021, 06:43 AM
Last Post: Gribouillis
  .remove() from a list - request for explanation InputOutput007 3 2,230 Jan-28-2021, 04:21 PM
Last Post: InputOutput007
  Style question on adherence to PEP 8 with whitespace near an "=" sign nilesh 6 3,942 Jan-12-2021, 11:11 PM
Last Post: snippsat
  Remove double quotes from the list ? PythonDev 22 8,794 Nov-05-2020, 04:53 PM
Last Post: snippsat
  Remove specific elements from list with a pattern Xalagy 3 2,702 Oct-11-2020, 07:18 AM
Last Post: Xalagy
  How to remove dict from a list? Denial 7 2,941 Sep-28-2020, 02:40 PM
Last Post: perfringo
  Superfluous whitespace found? CaptainCsaba 2 21,247 Mar-19-2020, 09:04 AM
Last Post: ak52

Forum Jump:

User Panel Messages

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