Python built-in data structure --- string

1. Make exe program

If the python script cannot be run on a machine that does not have python installed, package the script into an exe file to reduce the script’s dependence on the environment, and at the same time run faster, and to prevent the code from being stolen

(1) Install the third-party module pyinstaller

pip install pyinstaller
Insert picture description here

(2) Icon

Find your favorite icon in Alibaba's vector icon library .
Online image format conversion website to convert the image format to .ico
Insert picture description here

(3) Generate .exe

pyinstaller -F -i temper.ico temperature conversion.py # -i make the icon -F package the dependent files together
Pay attention to the location, I will put the icon together with the code here
Insert picture description here
Insert picture description here
Insert picture description here

2. Introduction to the built-in data structure

字符串str:单引号,双引号,三引号引起来的字符信息。三重引号也可以进行多行注释
数组array:存储同种数据类型的数据结构。[1, 2, 3], [1.1, 2.2, 3.3]
列表list:打了激素的数组, 可以存储不同数据类型的数据结构. [1, 1.1, 2.1, 'hello']
元组tuple:带了紧箍咒的列表, 和列表的唯一区别是不能增删改。
集合set:不重复且无序的。 (交集和并集)
字典dict:{“name”:"westos", "age":10
# 1. 字符串str
字符串或串(String)是由数字、字母、下划线组成的一串字符
s1 = 'hello'
s2 = "hello"
s3 = """
    *********************** 学生管理系统 ************************
"""
print(type(s1), type(s2), type(s3))

# 2. 列表List
li1 = [1, 2, 3, 4]
print(li1, type(li1))
li2 = [1, 2.4, True, 2e+5, [1, 2, 3]]
print(li2, type(li2))

# 3. 元组tuple
# 易错点: 如果元组只有一个元素,一定要加逗号。
t1 = (1, 2.4, True, 2e+5, [1, 2, 3])
print(t1, type(t1))
t2 = (1,)
print(t2, type(t2))

# 4. 集合set(无序,不重复)
set1 = {1, 2, 1, 2, 3, 1, 20}
print(set1)   # 不重复{1, 2, 20}
set2 = {1, 2, 3}
set3 = {2, 3, 4}
print("交集:", set2 & set3)
print("并集:", set2 | set3)

# 5. 字典dict: {“name”:"westos", "age":10}
# key和value, 键值对, 通过key可以快速找到value值。
user = {"name":'westos', 'age':10}
print(user, type(user))
print(user['name'])
print(user['age'])

Three. String

A string or string (String) is a string of characters composed of numbers, letters, and underscores. The most common type in Python. It can be created simply by enclosing characters between quotation marks (single, double, and triple quotation marks) .
escape signals : a backslash plus a single character can represent a special character, usually unprintable characters, commonly used mainly \ n \ t
Insert picture description here
erase the character strings : strings are immutable, only through Assign an empty string or use the del statement to clear or delete a string.
But there is no need to display the delete string, the string will be automatically released when the code that defines this string ends

Four. Basic characteristics of strings

# 1. 连接操作符和重复操作符:连接符( + ), 重复操作符( * ),计算长度 len()
连接操作符: 从原有字符串获得一个新的字符串
重复操作符:  创建一个包含了原有字符串的多个拷贝的新字符串
name = 'westos'
print('hello ' + name)
# 1元 + 1分 = 1元 + 0.01元 = 1.01元
print('hello' + str(1))
print("*" * 30 + '学生管理系统' + '*' * 30)

# 2. 成员操作符(in ,not in)
成员操作符用于判断一个字符或者一个子串(中的字符)是否出现在另一个字符串中。出现则返回 True,否则返回 False.
s = 'hello westos'
print('westos' in s)  # True
print('westos' not in s) # False
print('x' in s) # False

# 3. 正向索引和反向索引
索引(s[i] ):     获取特定偏移的元素
索引的分类:      正向索引, 反向索引
s = 'WESTOS'
print(s[0])  # 'W'
print(s[3]) # 'T'
print(s[-3]) # 'T'

# 4. 切片
回顾: 
    range(3):[0, 1, 2]
    range(1, 4): [1, 2, 3]
    range(1, 6, 2): [1, 3, 5]
    
切片: 切除一部分的内容
    s[start:end:step]
    s[:end]:
    s[start:]:
(1)切片S[i:j]提取对应的部分作为一个序列:
(2)如果没有给出切片的边界,切片的下边界默认为0,上边界为字符串的长度;扩展的切片S[i:j:k],其中i,j含义同上,k为递增步长;
(3)s[:]获取从偏移量为0到末尾之间的元素,是实现有效拷贝的一种方法;
(4)s[::-1]是实现字符串反转的一种方法;

总结: 
    s[:n]: 拿出前n个元素
    s[n:]: 除了前n个元素, 其他元素保留
    s[:]:从头开始访问一直到字符串结束的位置
    s[::-1]: 倒序输出
s = 'hello world'
print(s[1:3]) # 'el'
print(s[:3]) # 'hel'
print(s[:5])  # 拿出字符串的前5个字符
print(s[1:])  # 'ello world'
print(s[2:])  # 'llo world'
print(s[:])   # 拷贝字符串
print(s[::-1])

# 5. for循环访问
s = 'world'
count = 0
for item in s:
    count += 1
    print(f"第{count}个字符:{item}")

index

# 练习:用户输入一个字符串, 判断该字符串是否为回文字符串
# eg: "aba"是回文字符串, "abba"也是回文字符串。 "abc"不是回文字符串
while True:
    s = input('输入字符串:')
    result = "回文字符串" if s == s[::-1] else "不是回文字符串"
    print(s + "是" + result)

Insert picture description here

Five. String built-in method

(1) Judgment and conversion of character strings
Insert picture description here

# 1. 类型判断
s = 'HelloWORLD'
print(s.isalnum())  # True
print(s.isdigit())  # Flase
print(s.isupper())  # False

# 2. 类型的转换
print('hello'.upper())
print('HellO'.lower())
print('HellO WOrld'.title())
print('HellO WOrld'.capitalize())
print('HellO WOrld'.swapcase())

# 需求: 用户输入Y或者y都继续继续代码
# yum install httpd
choice = input('是否继续安装程序(y|Y):')
if choice.lower() == 'y':
    print("正在安装程序......")

(2) Matching at the beginning and end of the string
Insert picture description here

# startswith
url = 'http://www.baidu.com'
if url.startswith('http'):
    # 具体实现爬虫,感兴趣的话可以看request模块。
    print(f'{url}是一个正确的网址,可以爬取网站的代码')

# endswith:
# 常用的场景: 判断文件的类型
filename = 'hello.png'
if filename.endswith('.png'):
    print(f'{filename} 是图片文件')
elif filename.endswith('mp3'):
    print(f'{filename}是音乐文件')
else:
    print(f'{filename}是未知文件')

(3) Data cleaning of strings
Insert picture description here

数据清洗的思路:
    lstrip: 删除字符串左边的空格(指广义的空格: \n, \t, ' ')
    rstrip: 删除字符串右边的空格(指广义的空格: \n, \t, ' ')
    strip: 删除字符串左边和右边的空格(指广义的空格: \n, \t, ' ')
    replace: 替换函数, 删除中间的空格, 将空格替换为空。replace(" ", )
    >>> " hello ".strip()
    'hello'
    >>> " hello ".lstrip()
    'hello '
    >>> " hello ".rstrip()
    ' hello'
    >>> " hel        lo ".replace(" ", "")
    'hello'

(4) Position adjustment of character string
Insert picture description here

>>> "学生管理系统".center(50)
'                      学生管理系统                      '
>>> "学生管理系统".center(50, "*")
'**********************学生管理系统**********************'
>>> "学生管理系统".center(50, "-")
'----------------------学生管理系统----------------------'
>>> "学生管理系统".ljust(50, "-")
'学生管理系统--------------------------------------------'
>>> "学生管理系统".rjust(50, "-")
'--------------------------------------------学生管理系统'

(5) String search and statistics
Insert picture description here

>>> s = "hello world"
>>> s.find("llo")
2
>>> s.index("llo")
2
>>> s.find("xxx")
-1
>>> s.index("xxx")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
# find如果找到子串, 则返回子串开始的索引位置。 否则返回-1
# index如果找到子串,则返回子串开始的索引位置。否则报错(抛出异常).
>>> s.count("xxx")
0
>>> s.count("l")
3
>>> s.count("o")
2

(6) Separation and splicing of strings
Insert picture description here

>>> ip = "172.25.254.100"
# 分离
>>> ip.split('.')
['172', '25', '254', '100']
>>> items = ip.split('.')
>>> items
['172', '25', '254', '100']
# 拼接
>>> items
['172', '25', '254', '100']
>>> # 需求: 将四个数字用'-'拼接起来
>>> "-".join(items)
'172-25-254-100'

Exercise

"""
# 需求: 生成100个验证码, 每个验证码由2个数字和2个字母组成。

import random  #调用随机模块
random.choice("0123456789")
'6'
random.choice("0123456789") + random.choice('0123456789') + random.choice('abcdef')
'16b'

import string  #调用字符串模块
string.digits
'0123456789'
string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

random.sample(string.ascii_letters, 4)
['z', 'N', 'u', 't']

"".join(random.sample(string.ascii_letters, 4))  #拼接
'aMUF'
"".join(random.sample(string.digits, 2)) + "".join(random.sample(string.ascii_letters, 4))  #连接
'95sGFj'
"""
import random
import string
for i in range(100):
	print("".join(random.sample(string.digits, 2)) + "".join(random.sample(string.ascii_letters, 4)))
"""
 设计一个程序,用来实现帮助小学生进行算术运算练习,
 它具有以下功能:
 提供基本算术运算(加减乘)的题目,每道题中的操作数是随机产生的,
 练习者根据显示的题目输入自己的答案,程序自动判断输入的答案是否正确
 并显示出相应的信息。最后显示正确率。

1+2=?
3*6=?
"""
import random

count = int(input("请输入题数"))
right_count = 0
for i in range(count):
    num1 = random.randint(1, 10)
    num2 = random.randint(1, 10)
    symbol = random.choice(["+", "-", "*"])
    result = eval(f"{num1}{symbol}{num2}")
    question = f"{num1} {symbol} {num2} = ?"
    print(question)
    user_answer = int(input("Answer:"))
    if user_answer == result:
        print("Right")
        right_count += 1
    else:
        print("Error")
print("Right percent: %.2f%%" %(right_count/count*100))

Insert picture description here

Insert picture description here

while True:
    i = 0
    j = 0
    move = str(input("请输入移动顺序:"))
    move1=move.upper()
    for s in move1:
        if s == "R":
            i += 1
        elif s == "L":
            i -= 1
        elif s == "U":
            j += 1
        elif s == "D":
            j -= 1
        else:
            print("输入有误")
            break
    else:
        if i == 0 and j==0:
            print("true")
        else:
            print("false")

Insert picture description here

Insert picture description here

while True:
    s = input('请输入字符串:')
    s1=s.lower()
    s2=s1.replace(" ","")
    s3=s2.split(',')
    s4="".join(s3)
    s5=s4.split(":")
    s6="".join(s5)
    result="是回文串" if s6 == s6[::-1] else "不是回文字符串"
    print(s+result)

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_49564346/article/details/113619931