1,单引、双引都可以定义字符串
三引号允许一个字符串跨多行
s='''
<html>
<hand>
<title></title>
</hand>
<body>
</body>
</html>'''
print(type(s))
执行结果:
<class 'str'>
字符串内存分配
a='abc'
b='abc'
c=''+a
d=a+b
全是新内存
只要不是变量传递方式。带有字符串运算的都是新内存。因为python是边解释边执行。没有做内存优化,编译优化。所以,
只写一个字符串常量,也是新内存
2,可以使用中括号和下标来获取单个字符,截取字符串
s='不迟到,不早退'
print(s[s.__len__()-1])#获取最后一位
print(s[-s.__len__()])#获取第一位
print(s[2:5])#获取下标为2-4的字符
print(s[:])#获取所有 即冒号前后不写就取自然结果
print(s[3:2])#如果前面大于后面,则什么都不输出
执行结果:
退
不
到,不
不迟到,不早退
-
.format()格式化:
想输出{}则输出两个{ {}}例如:print('aaa{ {0}}'.format())
print('name:{0} age:{1} job:{2}'.format("tom",33,1));
word="hello word";
print("o出现的次数为:{0}".format(word.count("o",0,8)));
执行结果:
name:tom age:33 job:1
o出现的次数为:2
-
s=word="hello nihao word";
print(s.find('n'));#找n的下标
print(s.rfind('h')); #从右往左
# print(s.index('n',0,5));# 找不到报错
print(s.find('n',0,5)); #找不到-1
print(s.rfind('h',-13,-1));
print(word.replace('hello','hi')); #替换
print(s.title());#将每个单词首字母大写
print(s.capitalize()); #将第一个单词首字母大写
print("字符串的长度:{0}".format(len(s)));
执行结果:
6
8
-1
8
hi nihao word
Hello Nihao Word
Hello nihao word
字符串的长度:16
-
邮箱
l=email=input('请输入邮箱')
a=email.find("@");
b=email.find(".");
if a>b:
print("邮箱错误,@不能在.后面");
elif a==0:
print("邮箱错误,@不能在第一位");
elif a==-1:
print("邮箱错误,没有@");
elif b==-1:
print("邮箱错误,没有.");
else:
print("邮箱用户名为:{0}".format(l[:a]));
执行结果:
请输入邮箱[email protected]
邮箱用户名为:2309041414
-
str.startwith 返回bool 判断开头是否是
s=phone='15135356733'
if s.startswith('151'): #开始 bool
print('yes');
else:
print('no');
执行结果:
yes
str.endswith 返回bool 判断结尾是否是
phone='15135356733'
print(phone.endswith('151')); #结束 bool
执行结果:
False
-
忽略大小写
phone='[email protected]'
print(phone.lower().upper());# 转大写 小写 用于忽略大小写
执行结果:
[email protected]
填充
name='zhangsan'
print(name.center(20,'#'));
执行结果:
######zhangsan######
-
判断是否是字母和数字
name='hello word'; #判断是否是字母和文字
print(name.isalpha());
name='12321'; #判断是否数字和字母文字
print(name.isalnum());
执行结果:
False
True
-
.join 拼接