如何从文本文件中删除 ^M 并将其替换为下一行 [英] How to remove ^M from a text file and replace it with the next line

查看:52
本文介绍了如何从文本文件中删除 ^M 并将其替换为下一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含以下内容的文本文件:

So suppose I have a text file of the following contents:

Hello what is up. ^M
^M
What are you doing?

我想删除 ^M 并将其替换为后面的行.所以我的输出看起来像:

I want to remove the ^M and replace it with the line that follows. So my output would look like:

Hello what is up. What are you doing?

我如何在 Python 中执行上述操作?或者,如果有任何方法可以使用 unix 命令执行此操作,请告诉我.

How do I do the above in Python? Or if there's any way to do this with unix commands then please let me know.

推荐答案

''.join(somestring.split(r'\r'))

somestring.replace(r'\r','')

这假设您的字符串中有回车符,而不是文字^M".如果它是文字字符串^M",则将 r'\r' 替换为^M"

This assumes you have carriage return characters in your string, and not the literal "^M". If it is the literal string "^M" then substiture r'\r' with "^M"

如果你想让换行符消失,那么使用 r'\r\n'

If you want the newlines gone then use r'\r\n'

这是 Python 中非常基本的字符串操作,可能值得查看一些基本教程 http://mihirknows.blogspot.com.au/2008/05/string-manipulation-in-python.html

This is very basic string manipulation in python and it is probably worth looking at some basic tutorials http://mihirknows.blogspot.com.au/2008/05/string-manipulation-in-python.html

正如第一个评论者所说,给出一些您迄今为止尝试过的内容以及您对问题不了解的内容总是有帮助的,而不是直接寻求答案.

And as the first commenter said its always helpful to give some indication of what you have tried so far, and what you don't understand about the problem, rather than asking for an straight answer.

这篇关于如何从文本文件中删除 ^M 并将其替换为下一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆