Python 如何使用分隔符字符串拆分字符串

Python 如何使用分隔符字符串拆分字符串

一个字符串是由多个字符组成的,可以表示一个单词或一个完整的短语。与Java不同,Python中不需要显式地声明字符串,我们可以直接将字符串值赋给一个具体的字面值。

字符串是String类的一个对象,其中包含多个内置函数和方法来操作和访问字符串。

在本文中,我们将了解如何在Python中使用分隔符字符串拆分字符串。

使用split()方法

一种使用分隔符拆分字符串的方法是使用字符串类的内置方法split()。这个方法接受一个字符串值作为参数,并将更新后的分隔符字符串作为输出返回。

还有一个可选的参数表示分隔符。如果没有指定分隔符,默认情况下将空格视为分隔符。还有另一个可选参数maxsplit,它告诉我们用户希望进行多少次拆分。

示例1

在下面的示例中,我们输入一个由“-”分隔的字符串,并使用split()方法进行拆分。

str1 = "Welcome to Tutorialspoint"

print("The given input string is")
print(str1)

print("The string after split ")
print(str1.split())

输出

以上给定程序的输出是:

The given input string is
Welcome to Tutorialspoint
The string after split
['Welcome', 'to', 'Tutorialspoint']

示例2

以下是按照分隔符 # 拆分字符串的示例。

str1 = "Hello#how#are#you"

print("The given input string is")
print(str1)

print("The string after split ")
print(str1.split("#"))

输出

The given input string is  
Hello#how#are#you
The string after split
['Hello', 'how', 'are', 'you']

使用正则表达式

我们还可以使用正则表达式在Python中拆分字符串。为此,您需要使用re库的函数 split() 。它有两个参数,分隔符和输入字符串。它将更新后的字符串作为输出返回。

示例1

在下面给出的示例中,我们正在获取一个以“-”分隔的字符串输入,并使用 split() 方法进行分割,我们将maxsplit设置为1。

str1 = "Welcome to Tutorialspoint"

print("The given input string is")
print(str1)

print("The string after split ")
print(str1.split(' ',1))

输出

上述示例的输出为,

The given input string is
Welcome to Tutorialspoint
The string after split
['Welcome', 'to Tutorialspoint']

示例2

在下面给出的示例中,我们输入一个字符串并使用分隔符“ ”通过 re.split() 方法将其拆分。

import re
str1 = "Welcome to Tutorialspoint"

print("The given input string is")
print(str1)

print("The string after split ")
print(re.split(' ',str1))

输出

上述给定程序的输出是:

The given input string is
Welcome to Tutorialspoint
The string after splitted
['Welcome', 'to', 'Tutorialspoint']

示例3

在下面给出的示例中,我们将一个字符串作为输入,并使用分隔符” “使用 re.split() 方法将其拆分,同时使用 maxsplit 设置为1。

import re
str1 = "Welcome to Tutorialspoint"

print("The given input string is")
print(str1)

print("The string after split ")
print(re.split(' ',str1,1))

输出

以上给出的示例的输出为:

The given input string is
Welcome to Tutorialspoint
The string after split
['Welcome', 'to Tutorialspoint']

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程