在 Python 中用空格替換換行符

Preet Sanghavi 2022年5月17日
在 Python 中用空格替換換行符

在本教程中,我們將學習使用一種技術在 Python 中用空格替換換行符。

在 Python 中使用 replace() 函式將換行符替換為空格

讓我們使用一個帶有換行符的示例字串。

string1 = 'Hello\nWorld'

現在我們有了一個帶有換行符的字串。讓我們列印我們的示例字串。

print(string1)

上面的程式碼顯示了以下輸出,演示了新行。

Hello
World

我們現在將使用 replace() 函式將換行符替換為空格。我們將字串作為引數傳遞給函式,並將新的結果字串儲存在新變數中。

string2 = string1.replace('\n', ' ')

上面的程式碼將用空格替換我們字串中的所有換行符。我們得到一個沒有行字元的字串。

我們現在將列印新字串以檢視輸出。

print(string2)

我們在列印新字串時得到以下輸出。

Hello World

我們可以看到已經新增了一個空格來代替換行符。

因此,我們可以通過上述方法方便地將 Python 中的換行符替換為空格。

Preet Sanghavi avatar Preet Sanghavi avatar

Preet writes his thoughts about programming in a simplified manner to help others learn better. With thorough research, his articles offer descriptive and easy to understand solutions.

LinkedIn GitHub

相關文章 - Python String