5. Python的字符串

《Python编程的术与道:Python语言入门》视频课程
《Python编程的术与道:Python语言入门》视频课程链接:https://edu.csdn.net/course/detail/27845

字符串

python中的字符串是一个字符数组。

Python字符串的重要属性如下:

  • 字符串不可更改(immutable)
  • 支持Unicode字符– Python系统解释器的默认编码为unicode
  • 字符串是有序的–字符串记住插入字符的顺序
  • 通过索引访问–可以使用索引访问字符串中的各个字符

创建字符串

单引号和双引号

字符串包含单引号或双引号。

my_string = "This is a double-quoted string."
my_string
'This is a double-quoted string.'
my_string = 'This is a single-quoted string.'
my_string
'This is a single-quoted string.'

可以创建包含引号的字符串。

S1 = "We're open"   
S2 = "I said 'Wow!'"   
S3 = 'I said "Wow!"'  
print(S1)
print(S2)
print(S3)
We're open
I said 'Wow!'
I said "Wow!"
S4 =  'I said 'Wow!''  
print(S4)
  File "<ipython-input-4-351c4a153ea5>", line 1
    S4 =  'I said 'Wow!''
                     ^
SyntaxError: invalid syntax

可以在字符串内使用引号,只要它们与字符串周围的引号不匹配即可。

quote = "Linus Torvalds once said, \
         'Any program is only as good as it is useful.'"
quote
"Linus Torvalds once said,          'Any program is only as good as it is useful.'"

多行字符串

如果需要创建一个多行字符串,可以使用三重引号

三重单引号例子:

multiline_string = '''This is a string where I 
can confortably write on multiple lines
without worring about to use the escape character "\\" as in
the previsou example. 
As you'll see, the original string formatting is preserved.
'''

print(multiline_string)
This is a string where I 
can confortably write on multiple lines
without worring about to use the escape character "\" as in
the previsou example. 
As you'll see, the original string formatting is preserved.

三重双引号例子:

multiline_string = """This is a string where I 
can confortably write on multiple lines
without worring about to use the escape character "\\" as in
the previsou example. 
As you'll see, the original string formatting is preserved.
"""

print(multiline_string)
This is a string where I 
can confortably write on multiple lines
without worring about to use the escape character "\" as in
the previsou example. 
As you'll see, the original string formatting is preserved.

str()构造函数

可以使用str()的类型构造函数将Python中的几乎所有对象转换为字符串

S = str(35)
print(S)     
35
S = str(3+4j)
print(S)     
(3+4j)
S = str([1,2, 3])
print(S)    
[1, 2, 3]

字符串是数组 (Strings are Arrays)

像许多其他流行的编程语言一样,Python中的字符串是表示Unicode字符的字节数组。

但是,Python没有字符数据类型,单个字符(character)就是长度为1的字符串。

方括号可用于访问字符串中的元素。

注意下图中的正负索引:

在这里插入图片描述

a = "Hello, World!"
print(a[1])
e
# Indexing
S = 'ABCDEFGHI'
print(S[0])     # A
print(S[4])     # E
A
E
# Negative Indexing
S = 'ABCDEFGHI'
print(S[-1])    # I
print(S[-6])    # D
I
D

切片 (Slicing)

可以使用slice语法返回一定范围的字符。

指定开始索引和结束索引,以冒号分隔,以返回字符串的一部分。

b = "Hello, World!"
print(b[2:5])
llo

负索引 (Negative Indexing)

使用负索引从字符串末尾开始切片:

b = "Hello, World!"
print(b[-5:-2])
orl

字符串长度 (String Length)

要获取字符串的长度,请使用len()函数。

a = "Hello, World!"
print(len(a))
13

字符串常用方法

改变大小写

first_name = 'eric'

print(first_name)
print(first_name.title())
eric
Eric

通常以小写形式存储数据很好,然后根据需要更改来显示大小写。

first_name = 'eric'

print(first_name)
print(first_name.title())
print(first_name.upper())

first_name_titled = 'Eric'
print(first_name_titled.lower())
eric
Eric
ERIC
eric

注意:原字符串始终保持不变

print(first_name)
print(first_name_titled)
eric
Eric

你将经常看到此语法:其中变量名称后跟一个点,然后是操作的名称,后跟一组括号。 括号可能为空,也可能包含一些值。

 variable_name.action()

在这个例子中,“action”是**方法(method)**的名称。

方法可以对变量进行处理。

方法lowertitleupper都是已经写入Python语言的函数,它们可对字符串做操作。

稍后,我们将学习编写自己的方法。

#Examples:

S = 'Hello, World!'
print(S.lower())       # hello, world!
S = 'Hello, World!'
print(S.upper())       # HELLO, WORLD!
S = 'Hello, World!'
print(S.capitalize())	# Hello, world!
S = 'Hello, World!'
print(S.swapcase())		# hELLO, wORLD!
S = 'hello, world!'
print(S.title())		# Hello, World!
hello, world!
HELLO, WORLD!
Hello, world!
hELLO, wORLD!
Hello, World!

检查字符串 (Check String)

要检查字符串中是否存在特定短语或字符,可以使用innot in关键字。

txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)
True
txt = "The rain in Spain stays mainly in the plain"
x = "ain" not in txt
print(x) 
False

字符串替换

replace()方法将一个字符串替换为另一个字符串:

a = "Hello, World!"
print(a.replace("H", "J"))
Jello, World!

修改字符串

字符串不可更改(不可变)。 创建字符串后,将无法对其进行修改。

#Example: Strings are unchangeable

# TypeError: 'str' object does not support item assignment
S = 'Hello, World!'
S[1] = 'i'
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-24-3bef815a2651> in <module>
      3 # TypeError: 'str' object does not support item assignment
      4 S = 'Hello, World!'
----> 5 S[1] = 'i'


TypeError: 'str' object does not support item assignment
# TypeError: 'str' object doesn't support item deletion
S = 'Hello, World!'
del S[1]

字符串分割

split()方法在找到分隔符的实例时将字符串拆分为子字符串:

a = "Hello, World!"
print(a.split(",")) 
['Hello', ' World!']

合并(拼接)字符串

first_name = 'ada'
last_name = 'lee'

full_name = first_name + ' ' + last_name

print(full_name.title())
Ada Lee

加号将两个字符串合并为一个,称为拼接(concatenation)。

first_name = 'ada'
last_name = 'lovelace'
full_name = first_name + ' ' + last_name

message = full_name.title() + ' ' + \
        "was considered the world's first computer programmer."

print(message)
Ada Lovelace was considered the world's first computer programmer.

遍历字符串

要遍历字符串的字符,可使用简单的for循环。

#Example: Print each character in a string

S = 'Hello, World!'
for letter in S:
    print(letter, end=' ')
# H e l l o ,   W o r l d ! 
H e l l o ,   W o r l d ! 

字符串格式化

在Python中,可以通过三种主要方式将变量嵌入字符串中。

  • printf-style % 字符串格式化
  • str.format() 内置方法
  • f-String字符串格式化
# Use printf-style % string formatting
S = '%s is %d years old.' % ('Bob', 25)
print(S)    
Bob is 25 years old.
# Use format() Built-in Method
S = '{1} is {0} years old.'.format(25, 'Bob')
print(S)
Bob is 25 years old.
# Use f-String Formatter
name = 'Bob'
age = 25
S = f"{name} is {age} years old."
print(S) 
Bob is 25 years old.

Python2.6 开始,具有了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。相对于老版的%格式方法,它有很多优点。

1.在%方法中%s只能替代字符串类型,而在format中不需要理会数据类型;

2.单个参数可以多次输出,参数顺序可以不相同;

3.填充方式十分灵活,对齐方式十分强大;

4.官方推荐用的方式,%方式将会在后面的版本被淘汰。

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
My name is John, and I am 36
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
I want 3 pieces of item 567 for 49.95 dollars.
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
I want to pay 49.95 dollars for 3 pieces of item 567.
string_template = 'The result of the calculation of {calc} is {res}'
print("String Template: ", string_template)

print(string_template.format(calc='(3*4)+2', res=(3*4)+2))
String Template:  The result of the calculation of {calc} is {res}
The result of the calculation of (3*4)+2 is 14
更多介绍

有关字符串格式化的详细信息,请参阅有关字符串模块 string的官方联机文档。

转义字符 (Escape Character)

要在字符串中插入非法字符,请使用转义字符。

转义字符是反斜杠\,后跟要插入的字符。

非法字符的一个例子是在字符串内用双引号引起来的双引号。

如果在双引号包围的字符串中使用双引号,则会出现错误:

txt = "We are the so-called "Vikings" from the north."
  File "<ipython-input-38-56cdf4283a8e>", line 1
    txt = "We are the so-called "Vikings" from the north."
                                       ^
SyntaxError: invalid syntax

要解决此问题,使用转义符\"

txt = "We are the so-called \"Vikings\" from the north."
print(txt)
We are the so-called "Vikings" from the north.

Other escape characters used in Python:

CodeResult
Single Quote
\Backslash
\nNew Line
\rCarriage Return
\tTab
\bBackspace
\fForm Feed
\oooOctal value
\xhhHex
#Example: Escape special characters in Python

# Escape single quote
S = str('won\'t')
print(S)    # doesn't
# Escape double quote
S = str("\"Yes\", they said.")
print(S)    # "Yes", they said.
# Escape single and double quotes
S = str('"Isn\'t", they said.')
print(S)    # "Isn't", they said.
won't
"Yes", they said.
"Isn't", they said.
S = str('First line.\n\tSecond line.')
print(S)
First line.
	Second line.

空白字符

术语“空白”是指计算机知道的字符,但读者看不到。 最常见的空白字符是空格、制表符和换行符。

双字符组合"\t"使标签显示在字符串中。

print("Hello everyone!")
Hello everyone!
print("\tHello everyone!")
	Hello everyone!
print("Hello \teveryone!")
Hello 	everyone!

组合"\n"使换行符出现在字符串中。可以在字符串中的任何位置使用换行符。

print("Hello everyone!")
Hello everyone!
print("\nHello everyone!")
Hello everyone!
print("Hello \neveryone!")
Hello 
everyone!
print("\n\n\nHello everyone!")
Hello everyone!

去除空白字符

人们很容易在文本的开头或结尾包含无用的额外空格。 空格包括空格,制表符和换行符。

在开始使用它们之前,可以从字符串中去除这些空格。

可以从字符串的左侧、右侧或两侧剥离空白。

name = ' eric '

print(name.lstrip())
print(name.rstrip())
print(name.strip())
eric 
 eric
eric

以下内容会让操作更加清晰:

name = ' eric '

print('-' + name.lstrip() + '-')
print('-' + name.rstrip() + '-')
print('-' + name.strip() + '-')
-eric -
- eric-
-eric-

原始字符串 (Raw String )

如果不希望将\开头的字符解释为特殊字符(即不对其转义),则可以通过在第一引号之前添加r来使用原始字符串。

#Example:

S = 'C:\new\text.txt'
print(S)
# C:
# ew	ext.txt
C:
ew	ext.txt

\n被解释为换行符,\t被解释为制表符。 为避免这种情况,在第一个引号之前添加r使其成为原始字符串。

#Example:

S = r'C:\new\text.txt'
print(S)
# C:\new\text.txt
C:\new\text.txt
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bai666ai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值