[英]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 awayTeam meaning " word1 word2 " So sometimes both sides will have that format, sometimes only the right side, sometimes only the left side.
请注意,我有几个从网络上解析出来的字符串 ,其中一些具有相同的“样式/格式”或您将其称为
awayTeam的意思,意思是“ word1 word2”,因此有时双方都将具有该格式,有时仅右侧,有时只有左侧。
Don't remove whitespace then; 然后不要删除空格; use
str.strip()
on the results after splitting: 分割后在结果上使用
str.strip()
:
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. 这会分割成任意数量的空格,然后是
-
,然后是任意数量的空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.