字符串是 Python 中最常用的数据类型。可以使用引号( ' 或 " )来创建字符串。下面介绍字符串常用的实例:
#字符串格式化
name = "月是故乡明"
age = 28
print("我的名字是:%s\n我的年龄是:%d"%(name,age))
print("{1}:{0}".format("192.168.18.188",8888))
#Python startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。
# 如果参数 beg 和 end 指定值,则在指定范围内检查。语法格式:str.startswith(str, beg=0,end=len(string));
#strbeg -- 可选参数用于设置字符串检测的起始位置。strend -- 可选参数用于设置字符串检测的结束位置。
string = "空山新雨后,天气晚来秋。明月松间照,清泉石上流。竹喧归浣女,莲动下渔舟。随意春芳歇,王孙自可留。"
#以xx字符串开头,
print(string.startswith("松间",14,16))
#以XX字符串结尾
print(string.endswith("照"))
#判断字符串是不是纯数字
print(string.isdigit())
#去除两边指定的字符,得到一个新的字符,rstrip删除末尾,lstrip删除开头
str = "**晴烟漠漠柳毵毵,不那离情酒半酣。更把玉鞭云外指,断肠春色在江南。**"
new = str.strip("*")
new1 = str.rstrip("*")
new2 = str.lstrip("*")
print(new)
print(new1)
print(new2)
#字符串大写变小写lower(),字符串变大写upper()
en = "WELCOM TO BEIJING"
print(en.lower())
#字符串替换内容replace
print(en.replace("BEIJING","SHANGHAI"))
#split用于字符串的切割,返回列表。
data = "远看山有色,静听水无声。春去花还在,人来鸟不惊。"
print(data.split())