Python运算符”-”的功能包括
时间: 2023-05-25 16:04:29 浏览: 79
减法操作,用于从一个数中减去另一个数。例如,5-3的结果是2。在Python中,“-”运算符还可以用于将数字变为负数。例如,“-5”的结果是-5。此外,“-”运算符还可以用于字符串和列表的操作,用于删除元素。例如,s = "hello",s[1:] - "ell"的结果是"llo"。
相关问题
写出 Python 运算符 & 的两种功能
Python 运算符 `&` 具有两种功能:
1. 位运算与(and):对两个整数进行按位与操作,返回一个整数,每个位上的值都是对应位上两个整数的值都为 1 时才为 1,否则为 0。
示例代码:
```python
a = 0b1010 # 10 的二进制表示
b = 0b1100 # 12 的二进制表示
c = a & b # 按位与操作,c 的值为 0b1000,即 8
print(c) # 输出 8
```
2. 集合运算交(intersection):对两个集合进行交集运算,返回一个新集合,包含同时在两个集合中出现的元素。
示例代码:
```python
set1 = {'apple', 'banana', 'orange'}
set2 = {'banana', 'orange', 'watermelon'}
set3 = set1 & set2 # 交集运算,set3 的值为 {'banana', 'orange'}
print(set3) # 输出 {'banana', 'orange'}
```
需要注意的是,位运算与和集合交集运算都使用 `&` 运算符,但其操作数类型和功能不同,需要根据具体场景进行使用。
Python运算符%可以格式化字符串吗
是的,Python中的百分号(%)运算符还可以用于格式化字符串。这个功能通常称为“旧式字符串格式化”。
在旧式字符串格式化中,百分号(%)运算符的左侧是一个字符串,右侧是一个元组或字典。字符串中包含格式化占位符,用于指定如何将元组或字典中的值插入到字符串中。
下面是一些示例:
```python
# 使用元组进行字符串格式化
name = "John"
age = 25
print("My name is %s and I'm %d years old." % (name, age))
# 使用字典进行字符串格式化
person = {"name": "Mary", "age": 30}
print("My name is %(name)s and I'm %(age)d years old." % person)
```
输出:
```
My name is John and I'm 25 years old.
My name is Mary and I'm 30 years old.
```
在这个示例中,%s 和 %d 是格式化占位符。%s 表示字符串,%d 表示整数。元组中的第一个元素会替换第一个 %s,第二个元素会替换 %d,以此类推。在字典中,占位符使用 %(key)s 的形式,其中 key 是字典中的一个键。
需要注意的是,旧式字符串格式化已经过时,不建议使用。Python 3.6及以上版本中,推荐使用 f-string 或 str.format() 来进行字符串格式化。例如:
```python
# 使用 f-string 进行字符串格式化
name = "John"
age = 25
print(f"My name is {name} and I'm {age} years old.")
# 使用 str.format() 进行字符串格式化
person = {"name": "Mary", "age": 30}
print("My name is {} and I'm {} years old.".format(person["name"], person["age"]))
```
输出:
```
My name is John and I'm 25 years old.
My name is Mary and I'm 30 years old.
```