Skip to main content
 首页 » 编程设计

python之如何删除字符串python中的特定空格

2025年05月04日26bhlsheji

我正在像这样拆分和删除空格。

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

如果我将它们打印出来,它会显示:

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

但我也希望它看起来像这样:

homeTeam = "Hisingsbacka"  
awayteam = "Guldhedens IK"  

请注意我有几个从网络上解析出来的字符串,其中一些具有相同的“样式/格式”或任何你称之为 awayTeam 的东西,意思是“word1 word2” 所以有时双方都会有这种格式,有时只有右侧,有时只有左侧。

请您参考如下方法:

那么不要删除空格; split 后的结果使用str.strip():

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