【python】@property的介绍与使用

字符串

字符串是 Python 中最常用的数据类型。我们可以使用引号( ' 或 " )来创建字符串。创建字符串很简单,只要为变量分配一个值即可。例如:

var1 = 'Hello World!'
var2 = "Runoob"

 

Python 不支持单字符类型,单字符在 Python 中也是作为一个字符串使用。Python 访问子字符串,可以使用方括号 [] 来截取字符串,字符串的截取的语法格式如下:

变量[头下标:尾下标]

索引值以 0 为开始值,-1 为从末尾的开始位置。

 

字符串更新

#!/usr/bin/python3
 
var1 = 'Hello World!'
print ("已更新字符串 : ", var1[:6] + 'Runoob!')

输出:

已更新字符串 :  Hello Runoob!

startwith

startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。

语法:

str.startswith(substr, beg=0,end=len(string));

参数

  • str:检测的字符串。
  • substr:指定的子字符串。
  • beg:可选参数用于设置字符串检测的起始位置。
  • end:可选参数用于设置字符串检测的结束位置。

 

实例1:

#!/usr/bin/python3
 
str = "this is string example....wow!!!"
print (str.startswith( 'this' ))   # 字符串是否以 this 开头
print (str.startswith( 'string', 8 ))  # 从第九个字符开始的字符串是否以 string 开头
print (str.startswith( 'this', 2, 4 )) # 从第2个字符开始到第四个字符结束的字符串是否以 this 开头

实例2:

endwith

endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。

str.startswith(substr, beg=0,end=len(string));

参数

  • str -- 检测的字符串。
  • substr -- 指定的子字符串。
  • strbeg -- 可选参数用于设置字符串检测的起始位置。
  • strend -- 可选参数用于设置字符串检测的结束位置。

返回值

  • 如果检测到字符串则返回True,否则返回False。

 

实例1:

#!/usr/bin/python
 
str = "this is string example....wow!!!";
 
suffix = "wow!!!";
print(str.endswith(suffix));
print(str.endswith(suffix,20));
 
suffix = "is";
print(str.endswith(suffix, 2, 4));
print(str.endswith(suffix, 2, 6));

 

参考资料

1. @property的介绍与使用

 

posted @ 2023-05-30 10:21  苏格拉底的落泪  阅读(27)  评论(0编辑  收藏  举报