获得徽章 0
在Python中,swapcase()可以所有大写字符均转换为小写,小写字符均转换为大写。
```
# example string
string = "THIS SHOULD ALL BE LOWERCASE."
print(string.swapcase())
string = "this should all be uppercase."
print(string.swapcase())
string = "ThIs ShOuLd Be MiXeD cAsEd."
print(string.swapcase())
输出:
this should all be lowercase.
THIS SHOULD ALL BE UPPERCASE.
tHiS sHoUlD bE mIxEd CaSeD.
```
```
# example string
string = "THIS SHOULD ALL BE LOWERCASE."
print(string.swapcase())
string = "this should all be uppercase."
print(string.swapcase())
string = "ThIs ShOuLd Be MiXeD cAsEd."
print(string.swapcase())
输出:
this should all be lowercase.
THIS SHOULD ALL BE UPPERCASE.
tHiS sHoUlD bE mIxEd CaSeD.
```
展开
评论
1
在Python中使用super()或父类的名称调用父类的初始化
使用super函数调用父类的初始化方法。
```
class Parent:
def __init__(self, city, address):
self.city = city
self.address = address
class Child(Parent):
def __init__(self, city, address, university):
super().__init__(city, address)
self.university = university
child = Child('Peking University', 'Fudan University', 'Tsinghua University')
print(child.university) # Tsinghua University
```
使用父类的名称调用父类。
```
class Parent:
def __init__(self, city, address):
self.city = city
self.address = address
class Child(Parent):
def __init__(self, city, address, university):
Parent.__init__(self, city, address)
self.university = university
child = Child('Peking University', 'Fudan University', 'Tsinghua University')
print(child.university) # Tsinghua University
```
使用super函数调用父类的初始化方法。
```
class Parent:
def __init__(self, city, address):
self.city = city
self.address = address
class Child(Parent):
def __init__(self, city, address, university):
super().__init__(city, address)
self.university = university
child = Child('Peking University', 'Fudan University', 'Tsinghua University')
print(child.university) # Tsinghua University
```
使用父类的名称调用父类。
```
class Parent:
def __init__(self, city, address):
self.city = city
self.address = address
class Child(Parent):
def __init__(self, city, address, university):
Parent.__init__(self, city, address)
self.university = university
child = Child('Peking University', 'Fudan University', 'Tsinghua University')
print(child.university) # Tsinghua University
```
展开
3
2
在Python里,我们不需要和0比较长度,如果数值(如int)大于0,则默认为True。
```
def get_element_with_comparison(my_list):
if len(my_list) > 0:
return my_list[0]
def get_first_element(my_list):
if len(my_list):
return my_list[0]
elements = [1, 2, 3, 4]
first_result = get_element_with_comparison(elements)
second_result = get_element_with_comparison(elements)
print(first_result == second_result) # True
```
```
def get_element_with_comparison(my_list):
if len(my_list) > 0:
return my_list[0]
def get_first_element(my_list):
if len(my_list):
return my_list[0]
elements = [1, 2, 3, 4]
first_result = get_element_with_comparison(elements)
second_result = get_element_with_comparison(elements)
print(first_result == second_result) # True
```
展开
评论
点赞