Python中的字符串与列表

字符串

1.字符串的定义:

a = 'westos'
b = "what's"
c = """
    用户管理系统
    1.添加用户
    2.删除用户
    3.显示用户
    ....

"""
print(a)
print(b)
print(c)

【29】

2.字符串的特性:

s = 'hello' # 索引:0 1 2 3 4 索引从0开始
print(s[0])
print(s[1])
# 拿出最后 一个字符
print(s[4])
print(s[-1])
# s[start:stop:step] 从satrt开始到end -1结束
# 步长为step
print(s[0:3])
print(s[0:4:2])

【30】

# 显示所有的字符
print(s[:])
# 显示前3个字符
print(s[:3])
# 字符串的反转
print(s[::-1])

【31】

# 除了第一个字符之外的其他全部字符
print(s[1:])

# 重复
print(s * 10)

# 连接
print('hello ' + 'python')

【32】

# 成员操作符
print('he' in s)
print('aa' in s)
print('he' not in s)

# for循环遍历
for i in s:
    print(i)

【33】

3.字符串的常用方法

>>> 'hello'.istitle()
False
>>> 'hello'.isupper()
False
>>> 'Hello'.isupper()
False
>>> 'HELLO'.isupper()
True
>>> 'hello'.islower()
True
>>> 'Hello'.islower()
False
>>> a = 'Hello'.lower()
>>> a
'hello'
>>> a = 'Hello'.upper()
>>> a
'HELLO'
>>> a = 'Hello'.title()
>>> a
'Hello'
>>> 

【34】

e.g.

filename = 'hello.loggg'
if filename.endswith('.log'):
    print(filename)
else:
    print('error.file')

url = 'https://172.25.254.250/index.html'
if url.startswith('http://'):
    print('爬取内容~~')
else:
    print('不能爬取~~')

【35】

4.字符串的判断

[[:digit:]] [[:alpha:]]

e.g.只要有一个元素不满足,就返回False

print('weeeqwe32131'.isdigit())
print('42131321fsas'.isalpha())
print('weewqeq323213'.isalnum())

【36】

e.g.变量名定义是否合法:
1.变量名可以由字母 数字 下划线组成
2.变量名只能以字母或者下划线开头
s = ‘321csv_’ s[0] s[1:]
s = ‘asfasf%%’
‘_’
exit

while True:
    s = input('变量名:')
    if s == 'exit':
        print('exit')
        break
    if s[0].isalpha() or s[0] == '_':
        for i in s[1:]:
          if not (i.isalnum() or i == '_'):
              print('%s变量名不合法' %(s))
              break
        else:
            print('%s变量名合法' %(s))
    else:
        print('%s变量名不合法' %(s))

【37】

5.字符串的对齐

print('学生管理系统'.center(30))
print('学生管理系统'.center(30,'@'))
print('学生管理系统'.center(30,'&'))
print('学生管理系统'.ljust(30,'#'))
print('学生管理系统'.rjust(30,'#'))

【38】

6.字符串的替换

e.g.

s = 'hello world hello'

# find 找到子字符串,并返回最小的索引
print(s.find('hello'))
print(s.find('world'))
print(s.find('hello'))

# 替换字符串中的hello为redhat
print(s.replace('hello','redhat'))

【39】

7.字符串的统计

e.g.

print('hello'.count('l'))
print('hello'.count('ll'))
print(len('wfqfqfqfq'))

【40】

8.字符串的分离和连接

s = '172.25.254.250'
s1 = s.split('.')
print(s1)
print(s1[::-1])

date = '2019-8-28'
date1 = date.split('-')
print(date1)

# 连接 通过指定的连接符号 连接每个字符
print(''.join(date1))
print('/'.join(date1))
print('~~'.join('hello'))

【41】

e.g.字符串的练习
小米笔试编程题目

- 题目描述:
> 给定一个句子(只包含字母和空格), 将句子中的单词位置反转,
单词用空格分割, 单词之间只有一个空格,前>后没有空格。
比如: (1) “hello xiao mi”-> “mi xiao hello”
- 输入描述: 
> 输入数据有多组,每组占一行,包含一个句子(句子长度小于1000个字符)
- 输出描述: 
> 对于每个测试示例,要求输出句子中单词反转后形成的句子
示例1:
输入
    hello xiao mi
输出
    mi xiao hello

print(' '.join(input().split()[::-1]))

【42】

列表

1.列表的创建

数组:存储同一种数据类型的集合 scores = [34,56,90,100..]
列表(打了激素的数组):可以存储任意数据类型

list = [1,1.2,True,'westos']
print(list,type(list))

# 列表里面也可以嵌套列表
list2 = [1,1.2,True,'westos',[1,2,3,4]]
print(list2,type(list2))

【43】

2.列表的特性

service = ['http','ftp','ssh']

# 索引
# 正向索引
print(service[0])
# 反向索引
print(service[-1])

# 切片
print(service[::-1])
print(service[1:])
print(service[:-1])

# 重复
print(service * 3)

# 连接
service1 = ['mysql','firewalld']
print(service + service1)

# 成员操作符
print('firewalld' in service)
print('ftp' not in service1)

【44】

e.g.假定有下面这样的列表:

names = ['fentiao', 'fendai', 'fensi', 'apple']
输出结果为:'I have fentiao, fendai, fensi and apple.'

names = ['fentiao', 'fendai', 'fensi', 'apple']
print('I have ' + ','.join(names[:-1]) + ' and ' + names[-1])

【45】

e.g.输入某年某月某日(yyyy-MM-dd),判断这一天是这一年的第几天?

cal = input('请输入日期 yyyy-MM-dd: ')
date = cal.split('-') #拆分日期
#print(date)
year = int(date[0])
month = int(date[1])
day = int(date[2])
arr = [0,31,28,31,30,31,30,31,31,30,31,30,31]
num = 0
if ((year % 4 ==0) and (year % 100 !=0) or (year % 400 ==0)):
    arr[2] = 29
for i in range(1,len(arr)):
    if month > i:
        num += arr[i]
    else:
        num += day
        break
print('天数:',num)

【46】

3.列表元素的增加

service = ['http','ftp','ssh']

# append():追加一个元素到列表
service.append('firewalld')
print(service)

# extend():拉伸 追加多个元素到列表
service.extend(['mysql','nfs'])
print(service)

# insert():在指定索引处插入元素
service.insert(1,'https')
print(service)

【47】

4.列表元素的删除

>>> service = ['http','ftp','ssh']
>>> service.pop()
'ssh'
>>> service
['http', 'ftp']
>>> service.pop()
'ftp'
>>> service
['http']
>>> service = ['http','ftp','ssh']
>>> service.pop(0)
'http'
>>> service
['ftp', 'ssh']
>>> a = service.pop()
>>> a
'ssh'
>>> 

【48】

# remove():删除列表元素
service = ['http','ftp','ssh']
service.remove('ftp')
print(service)
# print(a)

# 从内存种删除一个元素
del service[1]
print(service)

【49】

5.列表的查看

service = ['http','samba','nfs','iscsi','http']

# 查看出现的次数
print(service.count('http'))

# 查看指定元素的索引值(可以指定索引范围)
print(service.index('nfs'))
print(service.index('http'))
print(service.index('http',2,5))

【50】

6.列表的修改

service = ['http','samba','nfs']
# 通过索引,重新赋值
service [0] = 'mysql'
print(service)

# 索引 切片 重复 连接 成员操作符 可迭代
# 通过切片
print(service[:2])
service[:2] = ['firewalld','iscsi']
print(service[:2])

【51】

7.列表的排序

import random
# 按照ASCII码排序
service = ['http','samba','nfs','iscsi','http']
service.sort()
print(service)

li = list(range(10))
print(li)

random.shuffle(li)   # 打乱
print(li)

【52】

e.g.用户管理的实现

1.后台管理员用户:admin,密码:westos
2.管理员登录后,可管理用户信息
3.用户信息包括:添加用户信息,删除用户信息,查看用户信息,退出
4.初始化用户信息:
users = ['root','redhat']
passwd = ['123','456']

print('管理员登录'.center(50,'*'))
aduser = input('Username: ')
adpasswd = input('Password: ')

#系统用户信息
users = ['root','redhat']
passwd = ['123','456']

if aduser == 'admin' and adpasswd == 'westos':
    print('管理员登录成功!')
    print('用户登录'.center(50, '*'))
    while True:
        print("""
            菜单
        1.添加用户信息
        2.删除用户信息
        3.查看用户信息
        4.退出
        """)
        choice = input('请输入你的选择: ')
        if choice == '1':
            print('添加用户信息'.center(50,'*'))
            adduser = input('添加用户名: ')
            if adduser in users:
                # print('用户%s已经存在' %adduser)
                print(f"用户{adduser}已经存在")
            else:
                addpasswd = input('密码: ')
                users.append(adduser)
                passwd.append(addpasswd)
                print(f"用户{adduser}添加成功")

        elif choice == '2':
            print('删除用户信息'.center(50, '*'))
            deluser = input('删除用户名: ')
            if deluser in users:
                delindex = users.index(deluser)
                users.remove(deluser)
                passwd.pop(delindex)
                print(f"删除用户{deluser}成功")
            else:
                print(f"用户{deluser}不存在")

        elif choice == '3':
            print('查看用户信息'.center(50, '*'))
            print('\t用户名\t密码')
            userlenth = len(users)
            for i in range(userlenth):
                print('\t%s\t%s' %(users[i],passwd[i]))

        elif choice == '4':
            exit()

        else:
            print('请输入正确的选择!')
else:
    print('管理员登录失败!')

【53】

e.g.栈的实现

1.入栈
2.出栈
3.栈顶元素
4.栈的长度
5.栈是否为空

stack = []
print('栈的实现'.center(50,'*'))
while True:
    print("""
        菜单
        1.入栈        2.出栈          3.栈顶元素
        4.栈长        5.栈是否为空     6.退出
    """)
    choice = int(input('请输入功能选项:'))
    if choice == 1:
        print('当前栈为:%s' %stack)
        addele = str(input('请输入入栈元素:'))
        stack.append(addele)
        print(f"元素{addele}已入栈!")
    elif choice == 2:
        print('当前栈为:%s' %stack)
        if len(stack) == 0:
            print('栈空!不能执行出栈操作!')
        else:
            delele = stack[-1]
            stack.pop()
            print(f"元素{delele}已出栈!")
            print('出栈操作后的新栈为:%s' %stack)
    elif choice == 3:
        if len(stack) == 0:
            print('栈空!无栈顶元素!')
        else:
            top = stack[-1]
            print('当前栈为:%s' %stack)
            print('栈顶元素为:%s' %top)
    elif choice == 4:
        length = len(stack)
        print('当前栈为:%s' %stack)
        print('栈长为%d' %length)
    elif choice == 5:
        if len(stack) == 0 :
            print('栈空!')
        else:
            print('当前栈为:%s' %stack)
            print('此栈不空!')
    elif choice == 6:
        print('退出!')
        break
    else:
        print('请输入正确的功能选项!')

【54】

python中常用的内置方法

In [8]: min(2,3,4,5)                                                    
Out[8]: 2

In [9]: max(2,3,4,5)                                                    
Out[9]: 5

In [10]: sum(range(1,101))                                              
Out[10]: 5050

In [11]: sum(range(1,101,2))                                            
Out[11]: 2500

In [12]: sum(range(2,101,2))                                            
Out[12]: 2550

#枚举:返回索引值和对应的value值
for i,v in enumerate('westos'):
    print(i,v)

#zip
s1 = 'abc'
s2 = '123'

for i in zip(s1,s2):
    # print(i)
    print(' '.join(i))

【55】

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值