1.变量名命名规则
# 中文是可以作为变量名的,但不建议姓名 = "hello"print(姓名)# 变量名可以由字母,数字或者下划线;# 变量名只能以字母或者下划线组成;# 变量名不能是python的关键字: eg: if, elif, else,# eg: while, for, break,continue,passa_1hello = "hello"print(a_1hello)# hell@ = "hello"# if = "hello"# while = "hello"
# break = "hello"
2.字符串的定义方式
字符串常用的转义符号:# \n:换行# \t: 一个tab键# \': '# \": "# 打印"hello"# 打印guido's# 打印"hello guido's python"print('"hello"')print("guido's")print("\"hello guido\'s python\"")
print("%s\t%s" % ("hello", "world"))
s = "hello"# 索引: 0,1,2,3,4, 索引值是从0开始的;print(s[0])print(s[4])print(s[-1]) # 拿出字符串的最后一个子符;# 切片print(s[0:3]) # 切片时规则为s[start:end:step],从start开始,到end-1结束, 步长为step;print(s[0:4:2])print(s[:]) # 显示所有子符print(s[:3]) # 显示前3个子符print(s[::-1]) # 对于字符串倒序输出;print(s[1:]) # 除了第一个子符之外, 其他全部显示;# 重复print(s*10)# 连接print("hello "+"world")# 成员操作符 s = "hello", in, not inprint('he' in s)print('aa' in s)
print('he' not in s)
字符串开头和结尾的匹配
# 找出字符串是否以xxxx结尾;s = "hello.jpg"print(s.endswith(('.png', '.jpg')))url1 = "http://www.baidu.com"url2 = "file:///mnt"url3 = "https://www.baidu.com"url4 = "ftp://www.baidu.com"# 以什么开头;print(url1.startswith(('https://', 'http://')))
print(url2.startswith("file://"))
字符串变量名判断
#[[:digit:]]#[[:upper:]]#[[:lower:]]#[[:alnum:]]#[[:space:]]s = 'hello'# 判断字符串里面的每个元素是否为什么类型, 一旦有一个元素不满足, 返回False;print("123".isdigit())print("123hfjhre".isdigit())print("HELLO".isupper())print("HELlO".isupper())# title是标题, 判断某个字符串是否为标题, 第一个字母为大写,其他为小写;p