从字符串内部删除所有换行符 [英] Remove all newlines from inside a string

查看:121
本文介绍了从字符串内部删除所有换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从字符串中删除所有换行符.我已经阅读了有关如何执行此操作的信息,但是由于某种原因,我似乎无法执行此操作.这是我正在逐步执行的操作:

I'm trying to remove all newline characters from a string. I've read up on how to do it, but it seems that I for some reason am unable to do so. Here is step by step what I am doing:

string1 = "Hello \n World"
string2 = string1.strip('\n')
print string2

我仍然在输出中看到换行符.我也尝试过rstrip,但是我仍然看到换行符.有人能阐明我为什么做错了吗?谢谢.

And I'm still seeing the newline character in the output. I've tried with rstrip as well, but I'm still seeing the newline. Could anyone shed some light on why I'm doing this wrong? Thanks.

推荐答案

strip仅从字符串的开头和结尾删除字符.您要使用replace:

strip only removes characters from the beginning and end of a string. You want to use replace:

str2 = str.replace("\n", "")

这篇关于从字符串内部删除所有换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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