1.变量名命名规则
# 中文是可以作为变量名的,但不建议
姓名 = "hello"
print(姓名)
# 变量名可以由字母,数字或者下划线;
# 变量名只能以字母或者下划线组成;
# 变量名不能是python的关键字: eg: if, elif, else,
# eg: while, for, break,continue,pass
a_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 in
print('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是标题, 判断某个字符串是否为标题, 第一个字母为大写,其他为小写;
print('Hello'.istitle())
print('HeLlo'.istitle())
print("hello".isnumeric())
print("111".isnumeric())
字符串变量名合法性练习题
# 变量名是否合法?
# 变量名可以由字母,数字或者下划线;
# 变量名只能以字母或者下划线开头;
#s = "hello@"
#1. 判断变量名的第一个元素是否为字母或者下划线; s[0]
#2. 如果第一个元素符合条件, 判断除了第一个元素的其他元素;s[1:]
# 1. for循环:依次遍历字符串的每一个元素;
# for i in "hello": # i: 'h', 'e', 'l' s[
# if i.isalpha():
# print(i)
# var = "hello'
# var = input("变量名:")
# # 判断第一个字符是否合法;
# if var[0] == "_" or var[0].isalpha():
# for char in var[1:]: # 判断除了第一个字符之外的其他字符 # char: e,l,l,o
# if char.isalnum() or char == "_":
# continue
# else:
# print('变量名%s不合法' %(var))
# break
# else:
# print('变量名%s合法' %(var))
# else:
# print("变量名不合法:第一个字符错误!")
var = input("变量名:").strip()
# 判断第一个字符是否合法;
if var[0] == "_" or var[0].isalpha():
for char in var[1:]: # 判断除了第一个字符之外的其他字符 # char: e,l,l,o
if not (char.isalnum() or char == "_"):
print('变量名%s不合法' %(var))
break
else:
print('变量名%s合法' %(var))
else:
print("变量名不合法:第一个字符错误!")
字符串搜索与替换
#find(), replace()
s = "hello world hello"
# find找到子串,并返回最小的索引值;
print(s.find("hello"))
print(s.find("world"))
# find找到子串,并返回最大的索引值;
print(s.rfind("hello"))
# 替换字符串中所有的“hello”为"westos"
print(s.replace("hello", "westos"))
删除无用的字符(读取或清洗数据)
#strip, lstrip, rstrip, replace
# strip: 删除字符串左边和右边的空格; 在这里空格是广义的: \n,\t,
s = " \t \n hello python \nhello"
print(s.strip())
# lstrip:删除字符串左边的空格;rstrip:删除字符串右边的空格
s = " \t \n hello python \nhello\n\t"
print(s.lstrip())
# 如何删除中间的空格? # 通过replace间接实现
s = "hello world hello"
print(s.replace(" ", ""))
字符串对齐
#ljust, rjust, center, format
print("学生管理系统".center(30))
print("学生管理系统".center(30, "*"))
print("学生管理系统".center(30, "#"))
print("学生管理系统".ljust(30, "*"))
print("学生管理系统".rjust(30, "*"))
print("hello %s" %('world'))
# 位置参数
print("{0} {1} {0} {0}".format(1,2))
字符串统计
字符串统计练习
# 给定一个字符串来代表一个学生的出勤纪录,这个纪录仅包含以下三个字符:
# 'A' : Absent,缺勤
# 'L' : Late,迟到
# 'P' : Present,到场
# 如果一个学生的出勤纪录中不超过一个'A'(缺勤)并且不超过两个连续的'L'(迟到),
# 那么这个学生会被奖赏。
# 你需要根据这个学生的出勤纪录判断他是否会被奖赏。
# 示例 1:
# 输入: "PPALLP"
# 输出: True
# 示例 2:
# 输入: "PPALLL"
# 输出: False
s = input("记录:")
# if s.count('A')<=1 and s.count('LLL')==0:
# print(True)
# else:
# print(False)
print(s.count('A')<=1 and s.count('LLL')==0)
字符串的分离和连接
s = '172.25.254.250'
# ['172', '25', '254', '250']列表数据类型
# split对于字符串进行分离, 分割符为"."
s1 = s.split(".")
print(s1[::-1])
date = '2018-04-25'
date1 = date.split("-")
# 倒序显示, 即反转;
date2 = date1[::-1]
print("date1:%s" %(date1))
print("date2:%s" %(date2))
# 连接, 通过指定的连接符, 连接每个字符串;
print("".join(date2))
print("/".join(date2))
print("/".join("hello"))
字符串的内置方法
print(min('hHello'))
print(max('hello'))
# python3中, 只支持数值类型比较大小;
# print(cmp('a', 'b'))
for i,j in enumerate("hello"):
print(i,j)
s1 = "hello"
s2 = "worldhs"
for i in zip(s1, s2):
print(i)
print(len("hello")) # 求字符串长度
10.练习题
1. 用户键盘输入一年份, 判断是否为闰年?
# - 如果是闰年, 则输出xxx是闰年;
# - 如果不是闰年, 则输出xxx不是闰年;
# 判断闰年的方法:
# 1). 能被4整除但不能被100整除;
# 2). 能被400整除;
year = int(input("Year:"))print('Likes')
7.求1~1000的和
num_sum = 0
for i in range(1, 1001): # i=1,2,3,4,.....1000
num_sum += i # num_sum = 0+1 0+1+2
print(num_sum)
8.回文数判断
# 题目要求:
#判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
# 示例:
#示例 1:
# 输入: 121
# 输出: true
#示例 2:
# 输入: -121
# 输出: false # 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
#示例 3:
# 输入: 10
# 输出: false
# 解释: 从右向左读, 为 01 。因此它不是一个回文数。
#进阶:
#你能不将整数转为字符串来解决这个问题吗?
# 方法1:
# # 121 == 121
# num = input('Num:')
# print(num == num[::-1])
# 方法2: 无需将整形转化为字符串类型print(num == back or num == back//10)