了解Python中的字符串

117 阅读7分钟

了解Python中的字符串

字符串是Unicode字符的序列。这个标准为每个字符提供了一个独特的代码,使它们可以被区分开来。在Python中,字符串被用来表示文本,可以包括空格、特殊字符和数字。

在 Python 中初始化字符串

我们通过使用单引号或双引号包围字符来创建字符串。也可以使用三重引号。

使用单引号

我们使用单引号定义字符串,如下所示。

string = 'Hello there' #single quotes
print(string)

输出。

Hello there

使用双引号

我们使用双引号定义字符串,如下所示。

string2 = "Double Quote String" #double quotes
print(string2)

下面是输出结果。

Double Quote String

使用三倍引号

string3 = '''Tripple Quote String''' # defining strings using tripple quotes
print(string3)

输出。

Tripple Quote String

请注意,三倍引号也可以用来指定多行字符串,如下所示。

# Multi-line strings
string4 = '''My name is Jane Doe,
    I like traveling so much'''

print(string4)
My name is Jane Doe,
    I like traveling so much

访问字符串中的字符

字符串可以被看作是字符的数组。这意味着我们可以通过在方括号中指定其索引来访问单个字符,如下图所示。

# printing the first character of the string
string = 'Hello there'
print(string[0])
H

由于Python允许负数索引,最后一个元素可以通过索引-1 ,第二个元素通过索引-2 ,以此类推,我们可以使用同样的方法来检索最后一个字符,如下图所示。

# printing the last index
string = 'Hello there'
print(string[-1])

输出。

e

打印一个字符的范围

我们使用slicing 来打印从一个给定索引到另一个索引的一系列字符。在这个技术中,我们指定了starting indexending index ,中间用冒号:

在下面的例子中,将被打印出来的字符串是在索引1和8之间。

#slicing 1st to 8th character
string = 'hello there'

# Print the string between index 1 to 8
print('string[1:8] = ', string[1:8])

输出。

string[1:8] =  ello th

Python字符串中的常用方法

lower() - 这个方法用于将一个按字母顺序排列的字符串转换为小写字母。字符串中的任何字符和数字都被忽略。

# original text
string = 'THIS IS TEXT IN UPPERCASE'

# print transformed string
print(string.lower())

下面是输出结果。

this is text in uppercase

upper() - 该方法将给定的文本转换为大写,并忽略特殊字符、数字和符号。

# initial string 
string = 'this text is in lowercase'

# transform to upper case
new_string = string.upper()

# print transformed string
print(new_string)

输出。

THIS TEXT IS IN LOWERCASE

len() - 该方法返回一个给定的输入字符串的长度,如下图所示。

string = 'programming is fun'

# getting the length of the string
print(len(string))
Output: 18

split() - 该方法将一个字符串的各个字符分离成一个列表。默认情况下,列表中的值是由白色空格分隔的。然而,你也可以使用逗号、哈希标签或任何其他字符。

在下面的例子中,我们将使用一个? 字符来分割字符串。

# initial string
string = 'Hello?world?this?is?my?test?for?the?game'

# splitting the string
new_string = string.split("?")

# printing the new string
print(new_string)

下面是输出结果。

['Hello', 'world', 'this', 'is', 'my', 'test', 'for', 'the', 'game']

join() - 这个方法将一个由分隔符指定的列表中的所有元素合并成一个字符串。这个函数需要一个可迭代对象作为参数。一个可迭代对象是一个可以一次返回单个元素的对象。

# iterable object 
object = ['Hello', 'world', 'this', 'is', 'my', 'test', 'for', 'the', 'game'] #list

# specifying the separator
separator = ' '

# Join where the comma occurs
print(separator.join(object))

输出。

Hello world this is my test for the game

find() - 该方法用于确定在给定的字符串中是否存在一个字符或一个值。它返回该值的第一次出现。如果没有找到该词或字符, 方法返回-1。find

例如,如果我们想在字符串hello world 中找到单词world 的出现,我们可以使用find 方法,如下图所示。

# string
string = 'Hello world'

# Find the occurence of world
y = string.find('world')

print(y)

输出。

6

在上面的代码中,该函数返回6 ,这是字符串world 的索引。

replace() - 这个方法用另一个短语替换了字符串中的一个短语。该方法需要3个参数;要替换的字符串,用什么替换,以及替换的次数。

如果我们没有说明替换的次数,该方法将替换该短语的所有出现。

# string
string = 'Hello world, this world are a nice world'

# replace world with people
y = string.replace('world', 'people')

# print the output
print(y)

输出。

Hello people, these people are very nice people

strip() - 该方法删除了任何跟踪或引导字符串的字符。默认情况下, 函数会删除空格,如下图所示。split()

string = "     hello world     " #string with extra spaces
x = string.strip()

print(x)

输出。

Hello world

一个特定的字符也可以作为一个参数传递给strip 方法。

string = "//////Hello world,,,,,"

x = string.strip("/,") # removes ///

print(x)

输出。

Hello world

Python字符串操作

本节讨论了可以用Python对字符串进行的一些操作。

字符串迭代

我们可以使用for 循环来迭代一个给定的字符串。我们可以通过迭代来确定字符串的长度,计算某个字符的出现次数,或者检查某个特定字母或字符的存在。

为了证明这一点,让我们在一个字符串中循环,并打印该字符串的每一个字符。

# Iterating through a string
for letter in 'Hello World':
    print(letter)

# count the number of letter
count = 0
string = 'Hello. how. is home from th lool above'
for letter in string:
    if(letter == 'o'):
        count+=1
print('The letter o occurs ' +str(count)+ ' times')   

输出。

H
e
l
l
o
 
W
o
r
l
d

The letter `o` occurs 7 times

串联

字符串连接涉及到一个字符串与另一个字符串的连接。我们使用+ 操作符来执行这一操作。

# concatenating Strings using the plus operator
# string 1
string1 = 'section'

#string 2
string2 = 'engineering'

#concatenated string
string3 = string1 + string2

#printing the output
print(string3)  

输出。

sectionengineering

字符成员

这是对一个给定的字符串进行的测试,以确定该字符串中是否存在一些字符。如果找到了这些字符,该方法返回true

我们通常使用关键字in 来检查字符成员。

# input string 
inputString = 'Hello World'

# string to find
stringToCheck = 'World'
stringToCheck2 = 'Google'

# membership test
x = stringToCheck in inputString
y = stringToCheck2 in inputString

#print output
print(x)
print(y)

下面是输出结果。

True
False

格式化字符串

在本节中,我们将讨论字符串格式化的三种主要方法。

使用'%'运算符

我们使用% ,通过用运算符替换变量中的内容来格式化字符串,如下图所示。

# Using % operator 
name = 'Dianne Sandra
print('My name is %s' %name)
My name is Dianne Sandra

使用'str.format'方法

这种方法是在Python 3.0 ,使程序员能够更有效地处理复杂的字符串操作。

str.format 是一种内置的方法,不需要额外的库。它支持通过替换某些值和变量来进行字符串操作。

这个函数演示如下。

# using format option 
print ("{} is a good platform.".format("Section Engineering Education"))

# substitution using variable names
print ('{name} is {age} years old and she is a {occupation}'
.format(name = 'Dianne', age = 19, occupation = 'programmer'))

输出。

Section Engineering Education is a good platform.
Dianne is 19 years old and she is a programmer

使用f-strings

引入于Python 3.6 ,f-strings允许将表达式嵌入字符串中。

它的名字是f-string ,这是因为其他表达式被嵌入的常数,其前缀是字母f

请看下面的例子。

# embbeding variables into string constants using f-string
string1 = 'Hello'
string2 = 'world'

# print the embeded string
print(f'{string1}  {string2}')
Output: Hello  world

结语

在这篇文章中,我们已经了解了 Python 中的字符串。我们讨论了如何初始化字符串,我们学习了可以在字符串上执行的操作,一些内置的方法,以及字符串格式化。你可以利用这些知识来制作强大的应用程序。