1.字符串的定义
a = ‘hello’
b = “westos”
c = ‘what’s’
d = “what’s”
e =
用户管理系统
1.添加用户
2.删除用户
3.显示用户
…
print(e)
print(type(e))
2.字符串的特性
s = ‘hello’
#索引:0 1 2 3 4(索引值是从0开始的)
print(s[0])
print(s[4])
print(s[-1]) # 拿出字符串的最后一个字符
#切片
print(s[0:3]) # 切片的原则 s[start?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 ’ + ‘python’)
#成员操作符
print(‘he’ in s)
print(‘aa’ in s)
print(‘he’ not in s)
#练习
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例:
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数
num = input('Num:')
print(num == num[::-1])
3.字符串的常用方法-大小写
>>> 'Hello'.istitle()
True
>>> 'Hello'.istitle()
True
>>> 'hello'.istitle()
False
>>> 'hello'.isupper()
False
>>> 'Hello'.isupper()
False
>>> 'HELLO'.isupper()
True
>>> 'hello'.upper()
'HELLO'
>>> 'Hello'.islower()
False
>>> 'hello'.islower()
True
>>> 'HELLO'.lower()
'hello'
>>> 'hello'.title()
'Hello'
4.字符串常用方法-开头和结尾的匹配
filename = input('请输入文件名:')
if filename.endswith('.log'): ##以.log结尾的文件名
print(filename)
elif filename.startswith('hello'): ##以hello开头的文件名
print(filename)
else:
print('error')
5.字符串的特性-去除左右两边的空格
注意:去除左右两边的空格,空格为广义的空格 包括:\n \t
>>> s = ' hello '
>>> s
' hello '
>>> s.lstrip() ##去掉左边空格
'hello '
>>> s.rstrip() ##去掉右边空格
' hello'
>>> s = '\n\thello '
>>> s
'\n\thello '
>>> s.strip() ##去掉两边空格包括:\n \t
'hello'
>>> s = 'helloh'
>>> s.strip('h') ##去掉两边h
'ello'
>>> s.strip('he') ##去掉两边h和e
'llo'
>>> s.lstrip('he') ##去掉左边h和e
'lloh'
6.字符串特性-判断数字
#只要其中有一个元素不满足,就返回False
print('1234'.isdigit()) ##判断输出是否为数字
print('hello'.isalpha()) ##判断输出是否为字母
print('hello31213'.isalnum()) ##判断输出是否为数字字母组合
#练习
仔细思考先不要看答案
变量名是否合法:
提示: 1.变量名可以由字母,数字或者下划线组成
2.变量名只能以字母或者下划线开头
s = ‘hello@’
1.判断变量名的第一个元素是否为字母或者下划线 s[0]
2.如果第一个元素符合条件,判断除了第一个元素之外的其他元素s[1:]
7.字符串的对齐
8.字符串的搜索和替换
s = ‘hello world hello’
#find找到子字符串,并返回最小的索引
print(s.find('hello')) ##从左向右找到hello
print(s.find('world')) ##从左向右找到world
print(s.rfind('hello')) ##从右向左找到hello
#替换字符串中的’hello’ 为’westos’
print(s.replace(‘hello’,‘westos’))
9.字符串的统计
print('hello'.count('l')) ##统计有几个l
print('hello'.count('ll')) ##统计由几个ll
print(len('westos')) ##统计有几个字符
10.字符串的分离和连接
s = '172.52.254.250'
s1 = s.split('.') ##以.分割将字符串分割
print(s1)
print(s1[::-1])
#连接:通过指定的连接符,连接每个字符串
date = ‘2019313’
print(’’.join(date1))
print(’/’.join(date1))
print(’@’.join(‘hello’))