在 Python 中從字串中刪除逗號

Suraj Joshi 2023年1月30日
  1. 使用 Python 中的 replace() 方法從字串中刪除逗號
  2. 使用 Python 中的 re 包從字串中刪除逗號
在 Python 中從字串中刪除逗號

本教程解釋瞭如何使用 Python 從字串中刪除逗號。要從 Python 中的字串中刪除逗號,我們可以使用 replace() 方法或 re 包。

我們將使用下面程式碼片段中的字串來演示如何在 Python 中從字串中刪除逗號。

my_string = "Delft, Stack, Netherlands"
print(my_string)

輸出:

Delft, Stack, Netherlands

使用 Python 中的 replace() 方法從字串中刪除逗號

Python str 類中的 replace() 方法用指定的子字串替換子字串並返回轉換後的字串。

replace() 方法的語法:

str.replace(old, new, count)

引數

old 子字串,在字串 str 中被替換
new 用於替換字串 str 中的 old 子字串的子字串
count 可選引數,指定 oldnew 替換的次數。如果未提供 count,該方法將用 new 子字串替換所有 old 子字串。

返回值

old 子字串替換為 new 子字串的字串。

示例:使用 str.replace() 方法從字串中刪除逗號

my_string = "Delft, Stack, Netherlands"
print("Original String is:")
print(my_string)

transformed_string = my_string.replace(",", "")
print("Transformed String is:")
print(transformed_string)

輸出:

Original String is:
Delft, Stack, Netherlands
Transformed String is:
Delft Stack Netherlands

它將字串 my_string 中的所有逗號替換為 ""。因此,刪除了字串 my_string 中的所有 ,

如果我們只想刪除 my_string 中的第一個 ,,我們可以通過在 replace() 方法中傳遞 count 引數來實現。

my_string = "Delft, Stack, Netherlands"
print("Original String is:")
print(my_string)

transformed_string = my_string.replace(",", "", 1)
print("Transformed String is:")
print(transformed_string)

輸出:

Original String is:
Delft, Stack, Netherlands
Transformed String is:
Delft Stack, Netherlands

由於在 replace() 方法中 count 的值設定為 1,它只會刪除字串 my_string 中的第一個逗號。

使用 Python 中的 re 包從字串中刪除逗號

在 Python 的 re pacakge 中,我們有 sub() 方法,該方法也可用於從字串中刪除逗號。

import re

my_string = "Delft, Stack, Netherlands"
print("Original String is:")
print(my_string)

transformed_string = re.sub(",", "", my_string)
print("Transformed String is:")
print(transformed_string)

輸出:

Original String is:
Delft, Stack, Netherlands
Transformed String is:
Delft Stack Netherlands

它將字串 my_string 中的所有 , 替換為 "",並刪除字串 my_string 中的所有逗號。

re.sub() 方法的第一個引數是要替換的子字串,第二個引數是要替換的子字串,第三個引數是要進行替換的字串。

作者: Suraj Joshi
Suraj Joshi avatar Suraj Joshi avatar

Suraj Joshi is a backend software engineer at Matrice.ai.

LinkedIn

相關文章 - Python String