Python海象运算符教程展示了如何在Python中使用海象运算符。
Python3.8引入了一个新的海象运算符:=。操作员的名字来源于它的侧面类似于海象的眼睛和象牙。
海象运算符创建一个赋值表达式。运算符允许我们为Python表达式中的变量赋值。它是一个方便的运算符,使我们的代码更加紧凑。
print(is_new := True)
我们可以一次分配和打印一个变量。
is_new = True print(is_new)
没有海象运算符,我们必须创建两条线。
Python海象读取输入
在下面的示例中,我们在while循环中使用海象运算符。
#!/usr/bin/python
words = []
while (word := input("Enter word: ")) != "quit":
words.append(word)
print(words)
我们要求用户写下附加到列表中的单词。
$ ./read_words.py Enter word: cloud Enter word: falcon Enter word: rock Enter word: quit ['cloud', 'falcon', 'rock']
这是一个示例输出。
带有if条件的Python海象
假设我们所有的单词必须至少有三个字符。
#!/usr/bin/python
words = ['falcon', 'sky', 'ab', 'water', 'a', 'forest']
for word in words:
if ((n := len(word)) < 3):
print(f'warning, the word {word} has {n} characters')
在示例中,我们使用海象运算符来测试单词的长度。如果一个单词少于三个字符,则会发出警告。我们一次性确定并分配一个单词的长度。
$ ./test_length.py warning, the word ab has 2 characters warning, the word a has 1 characters
Python海象阅读文件
在下一个示例中,我们使用海象运算符来读取文件。
falcon sky cloud water rock forest
words.txt文件中有一些单词。
#!/usr/bin/python
with open('words.txt', 'r') as f:
while line := f.readline():
print(line.rstrip())
该示例使用readline方法读取文件。海象运算符使代码更短。
Python海象遍历容器
在下面的示例中,我们在遍历字典列表时使用海象运算符。
#!/usr/bin/python
users = [
{'name': 'John Doe', 'occupation': 'gardener'},
{'name': None, 'occupation': 'teacher'},
{'name': 'Robert Brown', 'occupation': 'driver'},
{'name': None, 'occupation': 'driver'},
{'name': 'Marta Newt', 'occupation': 'journalist'}
]
for user in users:
if ((name := user.get('name')) is not None):
print(f'{name} is a {user.get("occupation")}')
在示例中,我们在字典中有None值。我们打印所有指定名称的用户。
$ ./traversing.py John Doe is a gardener Robert Brown is a driver Marta Newt is a journalist
有三个用户指定了他们的名字。
带有正则表达式的Python海象
在下面的示例中,我们在正则表达式中使用海象运算符。
#!/usr/bin/python
import re
data = 'There is a book on the table.'
pattern = re.compile(r'book')
if match := pattern.search(data):
print(f'The word {pattern.pattern} is at {match.start(), match.end()}')
else:
print(f'No {pattern.pattern} found')
我们搜索一个模式并将匹配项(如果找到)一次性分配给一个变量。
$ ./search.py The word book is at (11, 15)
在给定的索引处找到了单词书。
在本教程中,我们使用了Python海象运算符。
列出所有Python教程。
