您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python 字符串(String)

Python 字符串(String)

在本教程中,您将学习如何用Python创建、格式化、修改和删除字符串。此外,还将向您介绍各种字符串操作和函数。

Python中的字符串是什么?

字符串是字符序列。

字符只是一个符号。例如,英语具有26个字符。

计算机不处理字符,它们处理数字(二进制)。即使您可能在屏幕上看到字符,在内部它也被存储和操纵为0和1的组合。

字符到数字的这种转换称为编码,而相反的过程是解码。ASCII和Unicode是一些常用的编码。

在Python中,字符串是Unicode字符序列。引入Unicode包括所有语言中的每个字符并带来统一的编码。您可以从此处。

如何在Python中创建字符串?

可以通过将字符括在单引号或双引号中来创建字符串。Python中甚至可以使用三引号,但通常用于表示多行字符串和文档字符串。

# 下面这些都是等价的
my_string = 'Hello'
print(my_string)

my_string = "Hello"
print(my_string)

my_string = '''Hello'''
print(my_string)

# 三引号字符串可以扩展多行
my_string = """Hello, welcome to
           the world of Python"""
print(my_string)

运行该程序时,输出为:

Hello
Hello
Hello
Hello, welcome to
           the world of Python

如何访问字符串中的字符?

我们可以使用索引访问单个字符,并使用切片访问一系列字符。索引从0开始。尝试访问超出索引范围的字符将引发IndexError。索引必须是整数。我们不能使用float或其他类型,这将导致TypeError。

Python允许对其序列进行负索引。

索引-1表示最后一项,-2表示倒数第二项,依此类推。我们可以使用切片运算符(冒号)访问字符串中的一系列项目。

str = 'nhooo.com'
print('str = ', str)

#第一个字符
print('str[0] = ', str[0])

#最后一个字符
print('str[-1] = ', str[-1])

#切片第二到第五个字符
print('str[1:5] = ', str[1:5])

#切片从第6个到倒数第2个字符
print('str[5:-2] = ', str[5:-2])

输出结果:

str =  nhooo.com
str[0] =  n
str[-1] =  m
str[1:5] =  hooo
str[5:-2] =  .c

如果尝试访问超出范围的索引或使用十进制数,则会出现错误。

# 索引必须在范围内
>>> my_string[15]  
...
IndexError: string index out of range

# 索引必须是整数
>>> my_string[1.5] 
...
TypeError: string indices must be integers

通过考虑索引位于元素之间,可以最好地可视化切片,如下所示。

如果要访问范围,则需要索引,该索引将从字符串中切出一部分。

如何更改或删除字符串?

字符串是不可变的。这意味着字符串的元素一旦分配就无法更改。我们可以简单地将不同的字符串重新分配给相同的名称。

>>> my_string = 'nhooo.com'
>>> my_string[5] = 'a'
...
TypeError: 'str' object does not support item assignment
>>> my_string = 'Python'
>>> my_string
'Python'

我们不能删除或删除字符串中的字符。但是使用del关键字可以完全删除字符串。

>>> del my_string[1]
...
TypeError: 'str' object doesn't support item deletion
>>> del my_string
>>> my_string
...
NameError: name 'my_string' is not defined

Python字符串操作

字符串可以执行许多操作,这使它成为最常用的。

两个或多个字符串的串联

将两个或多个字符串连接为单个字符串称为串联。

+ 运算符在Python中执行串联操作。 简单地将两个字符串文字一起编写,也可以将它们串联在一起。

* 运算符可以用来重复字符串的特定次数。

str1 = 'Hello'
str2 ='World!'

# using +
print('str1 + str2 = ', str1 + str2)

# using *
print('str1 * 3 =', str1 * 3)

一起编写两个字符串文字也会像+运算符一样将它们串联在一起。

如果要在不同的行中连接字符串,可以使用括号。

>>> # 两个字符串文本在一起
>>> 'Hello ''World!'
'Hello World!'

>>> # 使用括号
>>> s = ('Hello '
...      'World')
>>> s
'Hello World'

遍历字符串

使用我们可以遍历字符串。这是一个计算字符串中“ l”数的示例。

count = 0
for letter in 'Hello World':
    if(letter == 'l'):
        count += 1
print(count,'letters found')

字符串成员资格测试

我们可以使用in关键字来测试字符串中是否存在子字符串。

>>> 'a' in 'program'
True
>>> 'at' not in 'battle'
False

使用Python的内置函数

可以使用sequence和string的各种内置函数。

一些常用的是enumerate()和len()。enumerate()函数的作用是:返回一个枚举对象。它以对的形式包含字符串中所有项的索引和值。这对于迭代很有用。

同样,len()返回字符串的长度(字符数)。

str = 'cold'

# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)

#字符数
print('len(str) = ', len(str))

Python字符串格式

转义序列

如果我们想打印一个文本-他说:“What's there?”-我们不能使用单引号或双引号。这将导致SyntaxError文本本身包含单引号和双引号。

>>> print("He said, "What's there?"")
...
SyntaxError: invalid syntax
>>> print('He said, "What's there?"')
...
SyntaxError: invalid syntax

解决此问题的一种方法是使用三引号。另外,我们可以使用转义序列。

转义序列以反斜杠开头,并且以不同的方式解释。如果我们使用单引号表示字符串,则必须对字符串内的所有单引号进行转义。双引号也是如此。这是表示上述文本的方法。

# 使用三个单引号
print('''He said, "What's there?"''')

# 转义单引号
print('He said, "What\'s there?"')

# 转义双引号
print("He said, \"What's there?\"")

这是Python支持的所有转义序列的列表。

Python中的转义序列
转义序列 描述
\newline 反斜杠和换行符被忽略
\\ 反斜杠
\' 单引号
\" 双引号
\a ASCII铃声
\b ASCII退格键
\f ASCII换页
\n ASCII换行
\r ASCII回车
\t ASCII水平制表符
\v ASCII垂直制表符
\ooo 具有八进制值的字符
\xHH 具有十六进制值HH的字符

这里有些示例

>>> print("C:\\Python32\\Lib")
C:\Python32\Lib

>>> print("This is printed\nin two lines")
This is printed
in two lines

>>> print("This is \x48\x45\x58 representation")
This is HEX representation

原始字符串忽略转义序列

有时我们可能希望忽略字符串中的转义序列。为此,我们可以将其放置在字符串的前面r或R前面。这意味着这是一个原始字符串,并且其中的任何转义序列都将被忽略。

>>> print("This is \x61 \ngood example")
This is a
good example
>>> print(r"This is \x61 \ngood example")
This is \x61 \ngood example

用format()方法格式化字符串

与string对象一起使用的format()方法非常通用,并且在格式化字符串方面功能非常强大。格式字符串包含大括号{}作为占位符或被替换的替换字段。

我们可以使用位置参数或关键字参数来指定顺序。

# 默认(隐式)顺序
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
print(default_order)

# 使用位置参数排序
positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
print('\n--- Positional Order ---')
print(positional_order)

# 使用关键字参数的排序
keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')
print('\n--- Keyword Order ---')
print(keyword_order)

format()方法可以具有可选的格式规范。它们使用冒号与字段名称分开。例如,我们可以在给定的空间中左对齐<,右对齐>或^将字符串居中。我们还可以将整数格式化为二进制,十六进制等,并且浮点数可以四舍五入或以指数格式显示。您可以使用大量的格式。请访问此处以方法所有。

>>> # 格式化整数
>>> "Binary representation of {0} is {0:b}".format(12)
'Binary representation of 12 is 1100'

>>> # 格式化浮点数
>>> "Exponent representation: {0:e}".format(1566.345)
'Exponent representation: 1.566345e+03'

>>> # 四舍五入
>>> "One third is: {0:.3f}".format(1/3)
'One third is: 0.333'

>>> # 字符串对齐
>>> "|{:<10}|{:^10}|{:>10}|".format('butter','bread','ham')
'|butter    |  bread   |       ham|'

旧样式格式

我们甚至可以像sprintf()在C编程语言中使用的旧样式一样格式化字符串。我们使用%运算符来完成此任务。

>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457

常见的Python字符串方法

字符串对象有许多可用的方法。上面提到的format()方法就是其中之一。常用的方法有lower()、upper()、join()、split()、find()、replace()等。这里是所有的完整列表中。

>>> "nhooo".lower()
'nhooo'
>>> "nhooo".upper()
'NHOOO'
>>> "This will split all words into a list".split()
['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list']
>>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
'This will join all words into a string'
>>> 'Happy New Year'.find('ew')
7
>>> 'Happy New Year'.replace('Happy','Brilliant')
'Brilliant New Year'

                                                                                                                                                                                                   


联系我
置顶