用Python中的新行替换空格

时间:2016-05-06 17:07:27

标签: python replace

我正在尝试将'\ s'替换为'\ n',但是当我打印line2时,它不会打印一行,并用新行替换空格。有人能说出我的语法有什么问题吗?

for line in fi:
    if searchString in line:
        line2 = line.replace('\s' , '\n') 
        print line2

2 个答案:

答案 0 :(得分:4)

.replace()替换字符串,您需要re.sub(..),例如:

for line in fi:
    if searchString in line:
        line2 = re.sub(r'\s' , '\n', line) 
        print line2

文档包含更多详细信息:https://docs.python.org/2/library/re.html#re.sub

答案 1 :(得分:4)

str.replace是正则表达式令牌,line.replace(' ', '\n') 无法理解。

执行:

class Game < ActiveRecord::Base
  # has the following attributes
  # starting_player_id:integer:index

  belongs_to :starting_player, class: Player
  has_many :players
end

class Player < ActiveRecord::Base
  # has the following attributes
  # game_id:integer:index

  has_one :starting_game, foreign_key: :starting_player_id, class: Game
  belongs_to :game
end