python基础
String
1.1 字符串格式化
问题: 输出 我叫xxx, 我今年xxx岁, 我的爱好是xxx
name = input("请输入您的名字:")
age = int(input("请输入您的年龄"))
hobby = input("请输入您的爱好")
第一种
%s 表示字符串占位符
%d 表示整数占位符
%f 表示小数占位符
s = "我叫%s, 我今年%d岁, 我的爱好是%s" % (name, age, hobby)
print(s)
第二种
s = "我叫{}, 我今年{}岁, 我的爱好是{}".format(name, age, hobby)
print(s)
format前有**.**
第三种
在python 3.5出现
s = f"我叫{name}, 我今年{age}岁, 我的爱好是{hobby}"
print(s)
1.2 字符串索引与切片
1.2.1索引
就是访问下标
s = "hello python"
注意: 从0开始
print(s[0])
print(s[1])
还可以从后面开始, 最后一个下标是-1
print(s[-1])
print(s[-2])
1.2.2切片
s = "hello world"
语法: array[start: end]
从start开始到end结束
注意: 区间为**[start, end)** 左闭右开
print(s[1:3])
print(s[1:4])
但你需要从开头到某位置 或者 某位置到结束时
print(s[:location])
print(s[location:])
print(s[:2])
print(s[2:])
如果想从右边到左边怎么办呢
切片提供了步长
语法:array[start:end :step]
if step > 0 从左向右 start < end
if step < 0 从右向左 end < start
step 大小表示隔多少步取一个
print(s[1:5:2])
print(s[5:1:-2])
1.3 字符串操作
s = "hello python"
- 字符串第一个字母大写
print(s.capitalize())
- 字符串每个单词首字母大写
print(s.title())
- 字符串所有变小写
print(s.lower())
- 字符串变大写
print(s.upper())
# 主要运用在验证码问题
wa = "utla" # 验证码
input_wa = input("请输入验证码:")
if (wa.upper() == input_wa.upper()):
print("验证成功")
else:
print("error!!!")
- 字符串分割
# 利用splite("以上面分割")
# 放回的是一个列表
s1 = s.split(" ") # 我以空格分隔
-
字符串去除头尾空白
空白:空格, \n, \t
# 利用strip()
# 返回一个字符串
s = " hello python "
s1 = s.strip()
print(s1)
# 可以用于账号和密码输入
account = input("请输入账号:")
password = input("请输入密码:")
if account == "admin":
if password == "123456":
print("correct")
else:
print("error")
else:
print("error")
###
输入:
admin
123456
###
- 字符串替换
# resplace(old, new)
s1 = s.replace(" ", "")
print(s1)
- 字符串查找
# 1. find("需要查找的字符串")
# 有返回第一个下标
# 无 返回-1
print(s.find("python"))
# 2. index("需要查找的字符串")
# 有 返回下标
# 无 直接报错
print(s.find("helll"))
# 3. in
print("hello" in s)
# 4. not in
print("hello" in s)
# 返回true or false
- 字符串判断
# startswith("字符串开头的char")
# 判断字符串开头的字符
if s.startswith("h"):
print("yes")
else:
print("no no no")
# endswith() 与上面一模一样
# isdigit()
# 判断字符串是否为整数
if s.isdigit():
print(int(s))
else:
print("error!!!")
# isdecimal()
# 判断是否为小数
if s.isdecimal():
print(double(s))
else:
print("error!!!")
1.4 字符串补充
- len()
# len()
# python 内置函数 表示字符串长度
print(len(s))
- join()
# join()
# python 内置函数 与split()相反
lst = ["java", "python", "c++", "hello"]
# 用_将lst拼接
s1 = '_'.join(lst)
print(s1)
总结
-
字符串格式化输出
- “字符串 + 占位符” % (占位符对应的内容)
- ”字符串 + 需要插入位置加{}“.format(位置内容)
- “字符串 + 需要插入位置加{填内容}”
-
字符串索引与切片
- s[index]
- s[start: end:step]
-
字符串常用操作
- capitalize()
- title()
- upper()
- lower()
-
字符串切割与替换
- strip()
- replace()
- split()
-
字符串查找与判断
- find()
- index()
- in
- not in
- startswith()
- endswith()
- isdigit()
- isdecimal()
-
字符串补充
- len()
nd:step]
- len()
-
字符串常用操作
- capitalize()
- title()
- upper()
- lower()
-
字符串切割与替换
- strip()
- replace()
- split()
-
字符串查找与判断
- find()
- index()
- in
- not in
- startswith()
- endswith()
- isdigit()
- isdecimal()
-
字符串补充
- len()
- join()