简体   繁体   中英

How to remove a specific white space in a string python

I am splitting and removing white spaces like this.

team =  "Hisingsbacka - Guldhedens IK"
homeTeam, awayTeam = team.replace(' ','').split("-")

If i were to print them out it would show:

homeTeam = "Hisingsbacka"  <-- This one is ok for this case
awayteam = "GuldhedensIK"  <-- not this one, space between the words needed as shown below

But I want it too look like this:

homeTeam = "Hisingsbacka" 
awayteam = "Guldhedens IK" 

Please do note i have several stings that are getting parsed from the web and some of them have the same "style/format" or whatever you would call it as meaning " word1 word2 " So sometimes both sides will have that format, sometimes only the right side, sometimes only the left side. ,其中一些具有相同的“样式/格式”或您将其称为意思,意思是“ word1 word2”,因此有时双方都将具有该格式,有时仅右侧,有时只有左侧。

Don't remove whitespace then; use str.strip() on the results after splitting:

team =  "Hisingsbacka - Guldhedens IK"
homeTeam, awayTeam = (t.strip() for t in team.split("-"))

You can just split for " - "

team =  "Hisingsbacka - Guldhedens IK"
homeTeam, awayTeam = team.split(" - " )

Seems like a regular expression might be a good way to go:

>>> import re
>>> SPLIT_RE = re.compile(r'\s*-\s*')
>>> SPLIT_RE.split('foo - bar')
['foo', 'bar']
>>> SPLIT_RE.split('foo -     bar')
['foo', 'bar']
>>> SPLIT_RE.split('foo-     bar')
['foo', 'bar']

this splits on any amount of whitespace followed by a - and then any amount of whitespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM