<< 第三天 || 第五天 >>

第四天

字符串

文本是字符串数据类型。任何写成文本的数据类型都是字符串。单引号、双引号或三引号下的任何数据都是字符串。有不同的字符串方法和内置函数来处理字符串数据类型。要检查字符串的长度,请使用 len() 方法。

创建一个字符串

letter = 'P'                # A string could be a single character or a bunch of texts
print(letter)               # P
print(len(letter))          # 1
greeting = 'Hello, World!'  # String could be made using a single or double quote,"Hello, World!"
print(greeting)             # Hello, World!
print(len(greeting))        # 13
sentence = "I hope you are enjoying 30 days of Python Challenge"
print(sentence)

多行字符串是通过使用三重单引号 (''') 或三重双引号 (""") 创建的。请参见下面的示例。

multiline_string = '''I am a teacher and enjoy teaching.
I didn't find anything as rewarding as empowering people.
That is why I created 30 days of python.'''
print(multiline_string)# Another way of doing the same thing
multiline_string = """I am a teacher and enjoy teaching.
I didn't find anything as rewarding as empowering people.
That is why I created 30 days of python."""
print(multiline_string)

字符串连接

我们可以将字符串连接在一起。合并或连接字符串称为串联。请参见下面的示例:

first_name = 'Asabeneh'
last_name = 'Yetayeh'
space = ' '
full_name = first_name  +  space + last_name
print(full_name) # Asabeneh Yetayeh
# Checking the length of a string using len() built-in function
print(len(first_name))  # 8
print(len(last_name))   # 7
print(len(first_name) > len(last_name)) # True
print(len(full_name)) # 16

字符串中的转义序列

在 Python 和其他编程语言中,\ 后跟一个字符是转义序列。让我们看看最常见的转义字符:

  • \n: 换行
  • \t:Tab 表示(8 个空格)
  • \\: 反斜杠
  • \':单引号 (')
  • \": 双引号 (")

现在,让我们通过示例查看上述转义序列的使用。

print('I hope everyone is enjoying the Python Challenge.\nAre you ?') # line break
print('Days\tTopics\tExercises') # adding tab space or 4 spaces
print('Day 1\t3\t5')
print('Day 2\t3\t5')
print('Day 3\t3\t5')
print('Day 4\t3\t5')
print('This is a backslash  symbol (\\)') # To write a backslash
print('In every programming language it starts with \"Hello, World!\"') # to write a double quote inside a single quote# output
I hope every one is enjoying the Python Challenge.
Are you ?
Days    Topics  Exercises
Day 1   5       5
Day 2   6       20
Day 3   5       23
Day 4   1       35
This is a backslash  symbol (\)
In every programming language it starts with "Hello, World!"

字符串格式化

旧式字符串格式(%运算符)

在 Python 中有许多格式化字符串的方法。在本节中,我们将介绍其中的一些。“%”运算符用于格式化包含在“元组”(固定大小列表)中的一组变量,以及格式字符串,格式字符串包含普通文本和“参数说明符”,特殊符号如“%s” , "%d", "%f", "%.number of digitsf".

  • %s - 字符串(或任何具有字符串表示形式的对象,如数字)
  • %d - 整数
  • %f - 浮点数
  • "%.number of digitsf" - 具有固定精度的浮点数
# Strings only
first_name = 'Asabeneh'
last_name = 'Yetayeh'
language = 'Python'
formated_string = 'I am %s %s. I teach %s' %(first_name, last_name, language)
print(formated_string)# Strings  and numbers
radius = 10
pi = 3.14
area = pi * radius ** 2
formated_string = 'The area of circle with a radius %d is %.2f.' %(radius, area) # 2 refers the 2 significant digits after the pointpython_libraries = ['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas']
formated_string = 'The following are python libraries:%s' % (python_libraries)
print(formated_string) # "The following are python libraries:['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas']"

新式字符串格式(str.format)

这种格式是在 Python 版本 3 中引入的。


first_name = 'Asabeneh'
last_name = 'Yetayeh'
language = 'Python'
formated_string = 'I am {} {}. I teach {}'.format(first_name, last_name, language)
print(formated_string)
a = 4
b = 3print('{} + {} = {}'.format(a, b, a + b))
print('{} - {} = {}'.format(a, b, a - b))
print('{} * {} = {}'.format(a, b, a * b))
print('{} / {} = {:.2f}'.format(a, b, a / b)) # limits it to two digits after decimal
print('{} % {} = {}'.format(a, b, a % b))
print('{} // {} = {}'.format(a, b, a // b))
print('{} ** {} = {}'.format(a, b, a ** b))# output
4 + 3 = 7
4 - 3 = 1
4 * 3 = 12
4 / 3 = 1.33
4 % 3 = 1
4 // 3 = 1
4 ** 3 = 64# Strings  and numbers
radius = 10
pi = 3.14
area = pi * radius ** 2
formated_string = 'The area of a circle with a radius {} is {:.2f}.'.format(radius, area) # 2 digits after decimal
print(formated_string)

字符串插值/f-Strings(Python 3.6+)

另一种新的字符串格式是字符串插值,f-strings。字符串以 f 开头,我们可以在其对应的位置注入数据。

a = 4
b = 3
print(f'{a} + {b} = {a +b}')
print(f'{a} - {b} = {a - b}')
print(f'{a} * {b} = {a * b}')
print(f'{a} / {b} = {a / b:.2f}')
print(f'{a} % {b} = {a % b}')
print(f'{a} // {b} = {a // b}')
print(f'{a} ** {b} = {a ** b}')

Python字符串作为字符序列

Python 字符串是字符序列,并与其他 Python 有序对象序列(列表和元组)共享它们的基本访问方法。从字符串(以及任何序列中的单个成员)中提取单个字符的最简单方法是将它们解包到相应的变量中。

解包字符

language = 'Python'
a,b,c,d,e,f = language # unpacking sequence characters into variables
print(a) # P
print(b) # y
print(c) # t
print(d) # h
print(e) # o
print(f) # n

按索引访问字符串中的字符 

在编程中计数从零开始。因此,字符串的第一个字母索引为零,字符串的最后一个字母是字符串的长度减一。

language = 'Python'
first_letter = language[0]
print(first_letter) # P
second_letter = language[1]
print(second_letter) # y
last_index = len(language) - 1
last_letter = language[last_index]
print(last_letter) # n

如果我们想从右端开始,我们可以使用负索引。-1 是最后一个索引。

language = 'Python'
last_letter = language[-1]
print(last_letter) # n
second_last = language[-2]
print(second_last) # o

切片Python字符串 

在 python 中,我们可以将字符串切片为子字符串。

language = 'Python'
first_three = language[0:3] # starts at zero index and up to 3 but not include 3
print(first_three) #Pyt
last_three = language[3:6]
print(last_three) # hon
# Another way
last_three = language[-3:]
print(last_three)   # hon
last_three = language[3:]
print(last_three)   # hon

反转字符串 

我们可以很容易地在 python 中反转字符串。

greeting = 'Hello, World!'
print(greeting[::-1]) # !dlroW ,olleH

切片时跳过字符 

通过将 step 参数传递给 slice 方法,可以在切片时跳过字符。

language = 'Python'
pto = language[0:6:2] #
print(pto) # Pto

字符串方法

有许多字符串方法允许我们格式化字符串。请参阅以下示例中的一些字符串方法: