Python中一些方法的整理(1)

一、使用方法修改字符串的大小写:

title() 以首字母大写的方式显示每个单词,即将每个单词的首字母都改为大写;

upper() 将字符串全部改为大写;

lower()将字符串全部改为小写;

二、删除空白:

rstrip() 能够删除字符串末尾的空白;

lstrip() 能够删除字符串开头部分的空白;

strip() 能够剔除字符串两端的空白;

三、使用函数str()避免类型错误:

str() 它让Python将非字符串值表示为字符串

age=23
str(age)

四、在列表中添加元素:

1、在列表末尾添加元素   使用方法append()

motorcycles.append('ducati')
print(motorcycles)

2、在列表中插入元素   使用方法insert()

方法insert()可在列表的任何位置添加新元素。为此,你需要指定新元素的索引和值。

motorcycles.insert(0,'ducati')
print(motorcycles)

五、在列表中删除元素:

1、使用del语句删除元素

如果知道要删除的元素在列表中的位置,可以使用del语句。

del motorcycles[0]
print(motorcycles[0])

2、使用方法pop()删除元素 

方法pop()可以删除列表末尾的元素,并让你能够接着使用它。

motorcycles=['honda','yamaha','suzuki']
print(motorcycles)
poped_motorcycles=motorcycles=motorcycles.pop()
print(motorcycles)
print(poped_motorcycles)

['honda','yamaha','suzuki']
['honda','yamaha']
suzuki

弹出列表中任何位置处的元素

实际上,你可以使用pop()来删除列表中任何位置的元素,只需在括号中指定要删除的元素的索引即可。

first_owned=motorcycles.pop(0)
print('The first motorcycles I owned was a'+first_owned.title()+'.')

3、根据值删除元素

如果你只知道要删除的元素的值,可使用方法remove() 。

motorcycles.remove('ducati')
print(motorcycles)

猜你喜欢

转载自blog.csdn.net/qq_41903671/article/details/81354445