Python基础入门(三)

Python基础入门(三)

一、本课目标
  • 理解并掌握 ”字符串“ 的概念及使用
  • 理解并掌握 ”列表“ 的概念及使用
  • 理解并掌握 “元组” 的概念及使用
  • 理解并掌握 “集合” 的概念及使用
二、字符串数据结构介绍
  • 字符串的定义

    • 字符串是一个有字符组成的有序序列。字符可以是,字母、数字、标点符号、或任何可打印的字符。字符串通过用于表示文本或文本数据
  • 关于数据结构中串的一些概念:

    • 串的长度:串的长度是指串中包含字符的数量。长度为零的串是空串。
    • 串的字符集:不同的编程语言和编码系统支持不同的字符集,例如ASCII、Unicode等
    • 串的索引:每个字符在串中都有一个唯一的位置,可以通过索引来访问,通常,索引从0开始,依次增加。
    • 串的特性:串通常是不变的,这意味着一旦创建,他们的内容不可更改。如果需要修改串的内容,通常会创建一个新的串。
    • 串的操作:串支持各种操作,包括连接、比较、切片、查找、替换、大小写转换、格式化等操作。这些操作允许对串进行处理、操作和转换。
三、字符串定义
  • 字符串是最常用的数据类型,使用引号(‘ 或 ”)来创建字符串

  • 创建字符串很简单,只要为变量分配一个值即可,例如:

    var1 = 'Hello World'
    var2 = "Student"
    
print(ord("a"))
print(ord("b"))
# 创建字符串
s1 = "abc123测试"
s2 = 'abc123测试'
s3 = '''
     abc
    123
   测试
'''
print(s3)

s4 = """
      abc
    123
   测试
"""
print(s4)

s5 = '"abc"'
s6 = "'abc'"
s7 = '"abc"\'abc\''
s8 = "\"abc\"'abc'"
s9 = ("abc"
      "def")
s10 = ('abc'
      'def')
s11 = ("abc\def")
print(s5, s6, s7, s8, s9, s10, s11)
四、字符串索引
  • 正向索引

    • 自左向右
    • 从0开始,依次递增
  • 反向索引

    • 自右向左
    • 从-1开始,依次递减
五、字符串切片
  • 不支持单字符串类型,单字符串在Python中也是作为一个字符串使用
  • 访问子字符串,可以使用方括号[ ]来截取字符串,字符串的截取的语法格式如下:
    • 变量[头下标:尾下标]
# 切片
s = "0123456789"
print(s[:])
print(s[0:])
print(s[:10])
print(s[0:10])
print(s[-10:])
六、字符串运算符
  • + 字符串连接

  • * 重复输出字符串

  • in 成员运算符 - 如果字符串中包含给定的字符串返回True

  • not in 成员运算符 - 如果字符串中不包含给定的字符串,返回True

    # 运算
    s = 'abc' + 'def' + '123'
    s = 'abc' * 3
    s = "=" * 30
    s = "abc" in "123abc456"
    s = "abc" not in "123abc45"
    s = "" in "123abc456"
    s = "abcdefg"
    print(s[1:5])
    print(s)
    
print("var1[0]:", var1[0])
print("已更新字符串:", var1[:6] + 'Google!')
print("var2[1:5]:", var2[1:5])
七、字符串格式化
  • %s 格式化字符串

  • %d 格式化整数

  • %f 格式化浮点数字,可指定小数后的精度

  • 案例

    # 格式化
    name = "小明"
    age = 10
    height = 1.83
    print("我叫小明, 今年10岁。")
    print("我叫%s,今年%d岁m, 身高%f米" % (name, age, height))
    print("我叫%5s,今年%d岁m, 身高%f米" % (name, age, height))
    print("我叫%-5s,今年%05d岁m, 身高%06.2f米" % (name, age, height))
    print(f'我叫{name}, 今年{age}岁, 身高{height}米')
    
  • f-string格式化字符串以f开头,后面跟着字符串,字符串中的表达式用大括号{}包起来,它会将变量或表达式计算后的值替代进去

  • 案例

    x = 1
    print(f'{x+1}')
    print(f'{x+1=}')
    print(f'{x}')
    print("abc", "def", 123, sep = '')
    print("abc" + "def" + str(123))
    
  • 练习

    import time
    for i in range(101):
        print('\r{:3}%'.format(i), end='')
        time.sleep(0.05)
    
a = "Hello"
b = "Python"
print("a + b 输出结果:", a + b)
print("a * 2输出结果:", a * 2)
print("a[1]输出结果:", a[1])
print("a[1:4]输出结果:", a[1:4])
if ("H" in a):
    print("H在变量a中")
else:
    print("变量不在a中")


if("M" not in a):
    print("M不在变量a中")
else:
    print("M在变量a中")

name = 'Google'
print('Hello %s'% name)
print(f'Hello {name}')
print(f'{1 + 2}')
x = 1
print(f'{x + 1}')
print(f'{x + 1 =}')
八、字符串函数-1
  • len(string)

    • 返回字符串长度
  • count(str)

    • 返回str在字符串里面出现的次数
  • startswith(substr)

    • 检查字符串是否是以指定子字符串substr开头
  • endswith(suffix)

    • 检查字符串是否以suffix结束
  • find(str)

    • 检查str是否包含在字符串中
# 字符串函数
print(len('abc12232'))
print(len(''))
print(len('\n'))
print(len('\\'))
print("ASDADSFDASDAS".count("A"))
print("aabb".startswith("aa"))
print("aabb".endswith("bb"))
print("aabb".endswith(""))

print("aabb".find("aa")) # 返回的是目标第一个索引值
print("aabb".find("bb"))
print("aabb".find("ab"))
print("aabb".find("bba"))

print("aabb".__contains__("ab"))
九、字符串函数-2
  • join(seq)

    • 以指定字符串作为分隔符,将seq中所有的元素(的字符串表示)合并为一个新的字符串
  • lower()、upper()

    • 转换字符串中所有字符为大(小)写
  • replace(old, new)

    • 将字符串中的old替换成new
  • split(str = “”)

    • 以str为分隔截取字符串
  • strip()

    • 在字符串上执行lstrip()和rstrip()
    print('-'.join('abcde'))
    print('+'.join(('1', '2', '3')))
    print("abcde".upper())
    print("abcde".lower())
    print("aabbccddee".replace('a', 'A'))
    print("aabbccddee".replace('a', ''))
    print("aa,bb,cc,dd".split(','))
    print("   \t\n   aabbccddee     ".strip())
    print("   \t\n   aabbccddee     ".lstrip())
    print("   \t\n   aabbccddee     ".rstrip())
    
    print("apple orange".capitalize()) # 首字母大写
    print("abc".center(10, "x"))
    
    print("www.google.com".count('o', 0, 10))
    
  • 扩展

    print("0123456789".find("56"))
    print("0123456789".find("56", 4))
    print("0123456789".find("56", 6))
    print("0123456789".index("56"))
    print("0123456789".index("56", 4))
    print("0123456789".index("56", 6)) # error
    
    print("aabbccddaa".find("aa"))
    print("aabbccddaa".rfind("aa"))
    print("0123456789".find("56", 0, 10))
    print("0123456789".find("56", 10, 0))
    print("0123456789".rfind("56", 0, 8))
    print("0123456789".rfind("56", 10, 0))
    
    print("a1".isalnum())
    print("  a1".isalnum())
    print("".isalnum())
    print("12中文".isalnum())
    print("123一二".isdigit())
    print("132一二壹千叁".isnumeric())
    print("abc 9+".islower())
    print("中文".islower())
    print(" \t\n".isspace()) # 空白符返回True
    
    print("abcd".center(10, "*"))
    print("abcd".ljust(10, "*"))
    print("abcd".rjust(10, "*"))
    
    print("88888das8888888".strip("8"))
    print("88888das8888888".lstrip("8"))
    print("88888das8888888".rstrip("8"))
    
    print(max('abc中'))
    print(min('abc8'))
    print("aaddsadsaasddffasaaadsaadsd".replace("aa", "AA", 2)) #这里的2为换的次数
    
    print("aa bb\tcc\ndd".split())
    print("aabbccdd".split('c', 1))
    print("aaBBccDD".swapcase())
    print("123".isdecimal())
    
  • 练习1:

    print("string example".capitalize())
    print("[google]".center(20, '*'))
    print("www.google.com".count('o'))
    print("www.google.com".count('o',0,10))
    print("this is string example".startswith('this'))
    print("this is string example".startswith('string', 8))
    print("this is string example".startswith('is', 2, 4))
    print('Google example…wow!!!'.endswith('!!'))
    print('Google example…wow!!!'.endswith('!!', 20))
    print('Google example…wow!!!'.endswith('wo', 0, 19))
    
    print("Google example…wow!!!".find("exam"))
    print("Google example…wow!!!".find("exam", 5))
    print("Google example…wow!!!".find("exam", 10))
    print("Google example…wow!!!".index("exam"))
    print("Google example…wow!!!".index("exam", 5))
    print("Google example…wow!!!".index("exam", 10))
    print("this is string example".rfind("is"))
    print("this is string example".rfind("is", 0, 10))
    print("this is string example".rfind("is", 10, 0))
    print("this is string example".find("is"))
    print("this is string example".find("is", 0, 10))
    print("this is string example".find("is", 10, 0))
    print("this is string example".rindex("is"))
    print("this is string example".rindex("is", 10))
    
  • 练习2:

    print("google2024".isalnum())
    print("www.google.com".isalnum())
    print("abc123".isalnum())
    print("abc 123".isalnum())
    print("abc#123".isalnum())
    print("".isalnum())
    print("123456".isalnum())
    print("abcdsa".isalnum())
    print("abc_dsa".isalnum())
    print("google".isalpha())
    print("google世界谷歌".isalpha())
    print("Google example...wow!!!".isalpha())
    print("HelloWorld".isalpha())
    print("Hello123".isalpha())
    print("Hello world".isalpha())
    print("Hello#world".isalpha())
    print("".isalpha())
    print("Hello_world".isalpha())
    print("12345".isdigit())
    print("Google example...wow!!!".isdigit())
    print("google2024".isnumeric())
    print("232422024".isnumeric())
    print("12123".isdigit())
    print("Google example...wow!!!".isdigit())
    
  • 练习3:

    print("Google example...wow!!!".islower())
    print("google example...wow!!!".islower())
    print("THIS IS STRING EXAMPLE....WOW!!!".isupper())
    print("THIS is string example....wow!!!".isupper())
    print(" ".isspace())
    print("Google example....wow!!!".isspace())
    print("-".join(("e", "f", "e", "l")))
    print("".join(("e", "f", "e", "l")))
    print("Google example".ljust(20,'*'))
    print("Google example".rjust(20,'*'))
    print("Google EXAMPLE....WOW!!!".lower())
    print("this is string example".upper())
    print("  this is string example  ".lstrip())
    print("88888888this is string example8888888".lstrip("8"))
    print("最大字符:" + max("Google"))
    print("最小字符:" + min("Google"))
    print("www.googel.com".replace("googel", "google"))
    print("this is string is is".replace("is", "was", 3))
    print("this is good   ".rstrip())
    print("this is good   ".rstrip('si oo')) # 删除不了字母d
    print("this is good   ".rstrip('sid oo'))# 从后往前索引先删除d再删除oo
    print("www.google.com/".rstrip('m/.'))
    print("banana,,,,,ssqqqww.....".rstrip(",.qsw"))
    print("*****this is string example*****".rstrip('*'))
    
    print("this is string example....wow!!".split())
    print("this is string example....wow!!".split('i', 1))
    print("this is string example....wow!!".split('w'))
    print("Google#Baidu#Taobao#Facebook".split('#', 1))
    print("*****this is **string** example*****".strip('*'))
    print("123abcgoogle321".strip('12'))
    print("PYTHON!!!".swapcase())
    print("python!!!".swapcase())
    print("abCDE--PyTHon".swapcase())
    print("google2024".isdecimal())
    print("23443434".isdecimal())
    
  • 统计任一字符串中字母、数字以及其他字符各出现的次数

    # 统计任一字符串中字母、数字以及其他字符各出现的次数
    a = 0
    b = 0
    c = 0
    for e in "abc123%^$":
        if e.isalpha():
            a += 1
        elif e.isdigit():
            b += 1
        else:
            c += 1
    else:
        print(f'字母{a}个,数字{b}个, 其他{c}个')
    
十、列表数据结构介绍
  • 列表是最常用的Python数据类型
  • 列表的数据项没有长度的限制
  • 列表的数据项不需要具有相同的类型
  • 列表中的数据项称为元素
  • 列表都可以进行的操作包括索引,切片,加,乘,检查成员等
十一、列表索引
  • 列表中的每个值都有对应的位置值,称之为索引,第一个索引是0,第二个索引是1,依次类推
    在这里插入图片描述
十二、列表切片
  • 通过[start : end]实现
  • 在这里插入图片描述
#列表
l = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(l[2:8])
print(l[-8:-2])
list = ['red', 'green', 'blue', 'yellow', 'white', 'black']
print(list[0])
print(list[1])
print(list[2])
print(list[-1])
print(list[-2])
print(list[-3])

nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(nums[0:4])

list = ['Google', 'Baidu', 'Zhihu', 'Taobao', 'Wiki']
print(list[1])
print(list[1:-2]) # 截取第二个到倒数第三个
十三、列表运算符
  • + 号用于组合列表
  • * 号用于重复列表
  • in 判断数据项是否存在于列表中
  • not in 判断数据项是否不存在于列表中
# 运算符
l1 = [1, 2, 3, 4, 5]
print(l1 + l1 + l1)
print(l1 * 3)
print(l1)
print(2 in l1, 2 not in l1)

l = []
print(l)
l = list("abc")
print(l)
十四、列表函数

在这里插入图片描述

l = []
l.append(1)
l.append(2)
l.append(3)
print(l)

l = [1, 2, 1, 1, 1, 3]
print(l.count(1))

l = []
l2 = [4, 5, 6]
l.append(1)
l.append(2)
l.extend([3])
l.extend(l2)
print(l)

l = list("aabbccddaacc")
print(l.index("d"))
l = [1, 2, 3]
l.insert(0, 4)
l.insert(5, 5)
print(l)

l = [1, 2, 3]
e = l.pop()
print(e, l)

l = [1,2,3,2]
e = l.remove(2)
print(e, l)

l = [1, 2, 3]
e = l.reverse()
print(e, l)

l = [1,2,3]
print(l)
l.clear()
print(l)

l1 = [1,2,3]
l2 = l1.copy()
l3 = l1
print(l1, l2, l3)

l = [1,2,2,2,3,4,2,2,5]
while l.count(2) > 0:
    l.remove(2)
print(l)

l = [1,2,2,2,3,4,2,2,5]
print(len(l))
l = list("dasdfassad")
print(l)
l.remove('d')
print(l)
del l[3]
print(l)
del l[1:4]
print(l)
l[1] = 'b'
print(l)
l = [1, 2, 3, 4, 5]
l[0] = 'a'
l[1:5] = list("adsd")
print(l)

l1 = [1, 2, 3]
l2 = [4, 5, 6]
l3 = l1 + l2
print(l1, l2, l3, l1 is l3)

for i in [1, 2, 3]:
    print(i, end='')
else:
    pass

l1 = [1, 2, 3]
l2 = [4, 5, 6]
l1 += l2
print(l1)

a = [1, 2]
b = [2, 3]
c = [2, 3]
print(a <= b)
print(b == c, b is c)
  • 练习1:

    list = ['Google', 'Baidu', 2019, 2023]
    list[2] = 2024
    print(list)
    list1 = ['Google', 'Yahoo', 'Taobao']
    list1.append('Baidu') # 在list1中后面追加字符
    print(list1)
    
    list = ['Google', 'Baidu', 2019, 2023]
    del list[2]
    print(list)
    
    print(len([1, 2, 3]))
    print([1, 2, 3] + [4, 5, 6])
    print(['Hi!' * 4])
    print(3 in [1, 2, 3])
    for x in [1, 2, 3]:
        print(x, end = "")
    else:
        pass
    
  • 练习2:

    L = ['Google', 'Yahoo', 'Taobao']
    print(L[2])
    print(L[-2])
    print(L[1:])
    
    squares = [1, 4, 9, 16, 25]
    squares += [36, 49, 64, 81, 100]
    print(squares)
    
    a = ['a', 'b', 'c']
    n = [1, 2, 3]
    x = [a, n]
    print(x)
    print(x[0])
    print(x[0][1])
    
  • 练习3:

    import operator
    a = [1, 2]
    b = [2, 3]
    c = [2, 3]
    print(operator.eq(a, b))
    print(operator.eq(c, b))
    
    list1 = ['Baidu', 'Google', 'Yahoo']
    print(len(list1))
    list2 = list(range(5))
    print(len(list2))
    
    list1, list2 = ['Google', 'Baidu', 'Taobao'], [456, 700, 200]
    print("list1 最大元素值:", max(list1))
    print("list2 最大元素值:", max(list2))
    print("list1 最小元素值:", min(list1))
    print("list2 最小元素值:", min(list2))
    
    
    aTuple = (123, 'Google', 'Baidu', 'Taobao')
    list1 = list(aTuple)
    print("列表元素:", list1)
    str = "Hello World"
    list2 = list(str)
    print("列表元素:", list2)
    
    queue = []
    # 添加字符ABC
    queue.append('A')
    queue.append('B')
    queue.append('C')
    print(queue)
    # ABC依次冒泡
    print(queue.pop(0))
    print(queue.pop(0))
    print(queue.pop(0))
    
  • 练习4:

    alist = [123, 'Google', 'Baidu', 'Taobao', 123]
    print("123元素个数;", alist.count(123))
    print("Google元素个数:", alist.count('Google'))
    
    list1 = ['Google', 'Baidu', 'Taobao']
    list2 = list(range(5))
    list1.extend(list2)
    print(list2)
    print("扩展后的列表", list1)
    
    language = ['French', 'English', 'Spanish']
    language_tuple = ('German', 'Portuguese')
    language_set = {'Chinese', 'Japanese'}
    language.extend(language_tuple)
    print('新列表:', language)
    language.extend(language_set)
    print('新列表:', language)
    
    list1 = ['Google', 'Baidu', 'Taobao']
    print('Baidu索引值为', list1.index('Baidu'))
    print('Taobao索引值为', list1.index('Taobao'))
    list1 = ['Google', 'Baidu', 'Taobao', 'Facebook', 'QQ']
    print('Baidu索引值为', list1.index('Baidu', 0))
    
    list1 = ['Google', 'Sina', 'Taobao']
    list1.insert(1, 'Baidu')
    print('列表插入元素后为:', list1)
    
    list1 = ['Google', 'Baidu', 'Taobao']
    list1.pop()
    print("列表现在为:", list1)
    list1.pop(1)
    print("列表现在为:", list1)
    
    list1 = ['Google', 'Yahoo', 'Taobao', 'Baidu']
    list1.remove('Taobao')
    print("列表现在为:", list1)
    list1.remove('Baidu')
    print("列表现在为:", list1)
    
    list1 = ['Google', 'Yahoo', 'Taobao', 'Baidu']
    list1.reverse()
    print("列表后转后:", list1)
    
  • 练习5:

    vowels = ['a', 'e', 'i', 'o', 'u']
    vowels.sort(reverse = True)
    print(vowels)
    
    def takeSecond(elem):
        return elem[1]
    random = [(2, 2), (3, 4), (4, 1), (1, 3)]
    random.sort(key = takeSecond)
    print('排序列表:', random)
    
    list1 = ['Google', 'Yahoo', 'Taobao', 'Baidu']
    list1.clear()
    print("列表清空后:", list1)
    
    list1 = ['Google', 'Yahoo', 'Taobao', 'Baidu']
    list2 = list1.copy()
    print("list2列表:", list2)
    
十五、总结
  • 掌握字符串的创建和操作方法
  • 掌握列表的创建和操作方法
  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI小白日记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值