Python入门.04.方法.md - 北方连萌

Python入门.04.方法.md

方法

方法是与数据类型相关的特殊函数。程序中出现的值,比如字符串和数字,可以根据其数据类型调用各种方法。

对象

对象是允许值携带各种伴随信息的东西。值的类型和可以使用该值的方法也作为辅助信息附加到对象上。Python的字符串和数字的值都被实现为“对象”,这为方便的编程提供了基础。

面向对象语言

可以将用于编程的数据表示为对象并将其用于编程的语言称为面向对象的语言。

调用方法

对象.方法(参数)

字符串方法

find()

返回要查找的值之中参数最出现的位置,以0为起始
若找不到则返回-1

print('hello'.find('l'))
print('hello'.find('h'))
print('hello world'.find('wor'))
print('hello world'.find('wol'))
2
0
6
-1

rfind()

返回要查找的值之中参数最出现的位置,以0为起始
若找不到则返回-1

print('hello'.rfind('l'))
print('hello'.rfind('h'))
print('hello world'.rfind('wor'))
print('hello world'.rfind('row'))
3
0
6
-1

count()

返回要查找的值之中参数出现的次数,以0为起始
若找不到则返回0

print('hello'.count('l'))
print('hello'.count('h'))
print('hello world'.count('wor'))
print('hello world'.count('row'))
2
1
1
0

replace()

text = 'I like this guy, and she likes this guy.'
print(text.replace('this', 'that', 1))
# 只替换一处,若找不到替换对象则不替换
print(text.replace('this', 'that'))
# 不指定数字,全数替换
print(text)
# 该方法返回的是新的字符串,原有字符串不变
I like that guy, and she likes this guy.
I like that guy, and she likes that guy.
I like this guy, and she likes this guy.

添加新评论

电子邮件地址不会被公开,评论内容可能需要管理员审核后显示。