前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python之字符串的基本使用

python之字符串的基本使用

作者头像
用户7886150
修改2021-01-11 10:17:56
7050
修改2021-01-11 10:17:56
举报
文章被收录于专栏:bit哲学院

参考链接: Python中的casefold()字符串

字符串的基本使用 

1、字符串的定义 

字符串 就是 一串字符,是编程语言中表示文本的数据类型在 Python 中可以使用 一对双引号 " 或者 一对单引号 ' 定义一个字符串 

  虽然可以使用 \" 或者 \' 做字符串的转义,但是在实际开发中: 

    如果字符串内部需要使用 ",可以使用 ' 定义字符串如果字符串内部需要使用 ',可以使用 " 定义字符串  可以使用 索引 获取一个字符串中 指定位置的字符,索引计数从 0 开始也可以使用 for 循环遍历 字符串中每一个字符 

 大多数编程语言都是用 " 来定义字符串 

str1 = "hello python"

str2 = '我的外号是"大西瓜"'

print(str2)

print(str1[6])

for char in str2:

    print(char)

2、字符串的常用操作 

在 ipython3 中定义一个 字符串,例如:hello_str = ""输入 hello_str. 按下 TAB 键,ipython 会提示 字符串 能够使用的 方法 如下: 

In [1]: hello_str.

hello_str.capitalize    hello_str.isidentifier  hello_str.rindex

hello_str.casefold      hello_str.islower       hello_str.rjust

hello_str.center        hello_str.isnumeric     hello_str.rpartition

hello_str.count         hello_str.isprintable   hello_str.rsplit

hello_str.encode        hello_str.isspace       hello_str.rstrip

hello_str.endswith      hello_str.istitle       hello_str.split

hello_str.expandtabs    hello_str.isupper       hello_str.splitlines

hello_str.find          hello_str.join          hello_str.startswith

hello_str.format        hello_str.ljust         hello_str.strip

hello_str.format_map    hello_str.lower         hello_str.swapcase

hello_str.index         hello_str.lstrip        hello_str.title

hello_str.isalnum       hello_str.maketrans     hello_str.translate

hello_str.isalpha       hello_str.partition     hello_str.upper

hello_str.isdecimal     hello_str.replace       hello_str.zfill

hello_str.isdigit       hello_str.rfind

 提示:正是因为 python 内置提供的方法足够多,才使得在开发时,能够针对字符串进行更加灵活的操作!应对更多的开发需求! 

3、字符串统计操作 

hello_str = "hello hello"

# 1. 统计字符串长度

print(len(hello_str))

# 2. 统计某一个小字符串出现的次数

print(hello_str.count("llo"))

print(hello_str.count("abc"))

# 3. 某一个子字符串出现的位置

print(hello_str.index("llo"))

# 注意:如果使用 index 方法传递的子字符串不存在,程序会报错

print(hello_str.index("abc"))

4、字符串判断方法 

方法说明string.isspace()如果 string 中只包含空格,则返回 Truestring.isalnum()如果 string 至少有一个字符并且所有字符都是字母或数字则返回 Truestring.isalpha()如果 string 至少有一个字符并且所有字符都是字母则返回 Truestring.isdecimal()如果 string 只包含数字则返回 True,全角数字string.isdigit()如果 string 只包含数字则返回 True,全角数字、⑴、\u00b2string.isnumeric()如果 string 只包含数字则返回 True,全角数字,汉字数字string.istitle()如果 string 是标题化的(每个单词的首字母大写)则返回 Truestring.islower()如果 string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 Truestring.isupper()如果 string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True

# 1. 判断空白字符

space_str = " "

print(space_str.isspace())

# 2. 判断字符串中是否只包含数字

# 1> 都不能判断小数

num_str = "1"

# num_str = "1.1"

# num_str = "\u00b2"

# num_str = "一千零一"

print(num_str)

# 2> 只能判断阿拉伯数字

print(num_str.isdecimal())

# 3> 可以判断(1)、\u00b2字符串

print(num_str.isdigit())

# 4> 可以判断中文数字

print(num_str.isnumeric())

5、查找和替换 

方法说明string.startswith(str)检查字符串是否是以 str 开头,是则返回 Truestring.endswith(str)检查字符串是否是以 str 结束,是则返回 Truestring.find(str, start=0, end=len(string))检测 str 是否包含在 string 中,如果 start 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回 -1string.rfind(str, start=0, end=len(string))类似于 find(),不过是从右边开始查找string.index(str, start=0, end=len(string))跟 find() 方法类似,不过如果 str 不在 string 会报错string.rindex(str, start=0, end=len(string))类似于 index(),不过是从右边开始string.replace(old_str, new_str, num=string.count(old))把 string 中的 old_str 替换成 new_str,如果 num 指定,则替换不超过 num 次

hello_str = "hello world"

# 1. 判断是否以指定字符串开始

print(hello_str.startswith("hello"))

# 2. 判断是否以指定字符结束

print(hello_str.endswith("World"))

# 3.查找指定字符串

# index 方法同样可以查找指定的字符串在大字符串中的索引

print(hello_str.find("llo"))

# index 方法如果指定的字符串不存在,会报错

# find 方法如果指定的字符串不存在,会返回 -1

print(hello_str.find("abc"))

# 替换字符串

# replace 方法会返回一个新的字符串,不会改变原有字符串的内容

print(hello_str.replace("world", "python"))

print(hello_str)

6、大小写转换 

方法说明string.capitalize()把字符串的第一个字符大写string.title()把字符串的每个单词首字母大写string.lower()转换 string 中所有大写字符为小写string.upper()转换 string 中的小写字母为大写string.swapcase()翻转 string 中的大小写

7、文本对齐与去除空白字符 

方法说明string.ljust(width)返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串string.rjust(width)返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串string.center(width)返回一个原字符串居中,并使用空格填充至长度 width 的新字符串 

方法说明string.lstrip()截掉 string 左边(开始)的空白字符string.rstrip()截掉 string 右边(末尾)的空白字符string.strip()截掉 string 左右两边的空白字符

# 要求:顺序并且居中对齐以下诗句

poem = ["登鹳雀楼",

        "王之涣",

        "白日依山尽",

        "黄河入海流",

        "欲穷千里目",

        "更上一层楼"]

for poem_str in poem:

    # print(poem_str.center(10))

    print("|%s|" % poem_str.center(10, " "))

    # print("|%s|" % poem_str.ljust(10, " "))

    # print("|%s|" % poem_str.rjust(10, " "))

print()

print()

poem1 = ["\t\n登鹳雀楼",

        "王之涣",

        "白日依山尽\t\n",

        "黄河入海流",

        "欲穷千里目",

        "更上一层楼"]

for poem_str1 in poem:

    # 先使用 strip 方法去除字符串中的空白字符

    # 在使用 center 方法居中显示文本

    print("|%s|" % poem_str1.strip().center(10, " "))

8、拆分和连接 

方法说明string.partition(str)把字符串 string 分成一个 3 元素的元组 (str前面, str, str后面)string.rpartition(str)类似于 partition() 方法,不过是从右边开始查找string.split(str="", num)以 str 为分隔符拆分 string,如果 num 有指定值,则仅分隔 num + 1 个子字符串,str 默认包含 ‘\r’, ‘\t’, ‘\n’ 和空格string.splitlines()按照行(’\r’, ‘\n’, ‘\r\n’)分隔,返回一个包含各行作为元素的列表string.join(seq)以 string 作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串

# 1. 将字符串中空白字符全部去掉

# 2. 使用 " " 作为分隔符,拼接成整齐得字符串

poem_str = "登鹳雀楼\t 王之涣 \t 白日依山尽 \t \n 黄河入海流 \t\t 欲穷千里目 \n 更上一层楼"

print(poem_str)

# 1. 拆分字符串

poem_list = poem_str.split()

print(poem_list)

# 2. 合并字符串

result = " ".join(poem_list)

print(result)

9、字符串的切片 

切片 方法适用于 字符串、列表、元组 

  切片 使用 索引值 来限定范围,从一个大的 字符串 中 切出 小的 字符串列表 和 元组 都是 有序 的集合,都能够 通过索引值 获取到对应的数据字典 是一个 无序 的集合,是使用 键值对 保存数据  

字符串[开始索引:结束索引:步长]

注意: 

指定的区间属于 左闭右开 型 [开始索引, 结束索引) => 开始索引 >= 范围 < 结束索引 

  从 起始 位开始,到 结束位的前一位 结束(不包含结束位本身) 从头开始,开始索引 数字可以省略,冒号不能省略到末尾结束,结束索引 数字可以省略,冒号不能省略步长默认为 1,如果连续切片,数字和冒号都可以省略 

索引的顺序和倒序 

在 Python 中不仅支持 顺序索引,同时还支持 倒序索引所谓倒序索引就是 从右向左 计算索引 

  最右边的索引值是 -1,依次递减  

演练需求 

  截取从 2 ~ 5 位置 的字符串  

  截取从 2 ~ 末尾 的字符串  

  截取从 开始 ~ 5 位置 的字符串  

  截取完整的字符串  

  从开始位置,每隔一个字符截取字符串  

  从索引 1 开始,每隔一个取一个  

  截取从 2 ~ 末尾 - 1 的字符串  

  截取字符串末尾两个字符  

  字符串的逆序(面试题)  

答案 

num_str = "0123456789"

# 1. 截取从 2 ~ 5 位置 的字符串

print(num_str[2:6])

# 2. 截取从 2 ~ `末尾` 的字符串

print(num_str[2:])

# 3. 截取从 `开始` ~ 5 位置 的字符串

print(num_str[:6])

# 4. 截取完整的字符串

print(num_str[:])

# 5. 从开始位置,每隔一个字符截取字符串

print(num_str[::2])

# 6. 从索引 1 开始,每隔一个取一个

print(num_str[1::2])

# 倒序切片

# -1 表示倒数第一个字符

print(num_str[-1])

# 7. 截取从 2 ~ `末尾 - 1` 的字符串

print(num_str[2:-1])

# 8. 截取字符串末尾两个字符

print(num_str[-2:])

# 9. 字符串的逆序(面试题)

print(num_str[::-1])

10、公共方法 

Python 内置函数 

Python 包含了以下内置函数: 

函数描述备注len(item)计算容器中元素个数del(item)删除变量del 有两种方式max(item)返回容器中元素最大值如果是字典,只针对 key 比较min(item)返回容器中元素最小值如果是字典,只针对 key 比较cmp(item1, item2)比较两个值,-1 小于/0 相等/1 大于Python 3.x 取消了 cmp 函数

注意 

字符串 比较符合以下规则: “0” < “A” < “a” 

运算符 

运算符Python 表达式结果描述支持的数据类型+[1, 2] + [3, 4][1, 2, 3, 4]合并字符串、列表、元组*[“Hi!”] * 4[‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]重复字符串、列表、元组in3 in (1, 2, 3)True元素是否存在字符串、列表、元组、字典not in4 not in (1, 2, 3)True元素是否不存在字符串、列表、元组、字典> >= == < <=(1, 2, 3) < (2, 2, 3)True元素比较字符串、列表、元组

注意 

in 在对 字典 操作时,判断的是 字典的键in 和 not in 被称为 成员运算符 

成员运算符 

成员运算符用于 测试 序列中是否包含指定的 成员 

运算符描述实例in如果在指定的序列中找到值返回 True,否则返回 False3 in (1, 2, 3) 返回 Truenot in如果在指定的序列中没有找到值返回 True,否则返回 False3 not in (1, 2, 3) 返回 False

注意:在对 字典 操作时,判断的是 字典的键 

11、完整的 for 循环语法 

在 Python 中完整的 for 循环 的语法如下: 

for 变量 in 集合:

    循环体代码

else:

    没有通过 break 退出循环,循环结束后,会执行的代码

for num in [1, 2, 3]:

    print(num)

    if num == 2:

        break

else:

    # 如果循环体内部使用 break 退出了循环

    # else 下方的代码不会被执行

    print("会执行吗?")

print("循环结束")

students = [

    {"name": "阿土",

     "age": 20,

     "gender": True,

     "height": 1.7,

     "weight": 75.0},

    {"name": "小美",

     "age": 19,

     "gender": False,

     "height": 1.6,

     "weight": 45.0},

]

# 在学员列表中搜索指定的姓名

# find_name = "阿土"

find_name = "张三"

for stu_dict in students:

    print(stu_dict)

    # 判断当前遍历的字典中姓名是否为find_name

    if stu_dict["name"] == find_name:

        print("找到了 %s" % find_name)

        # 如果已经找到,应该直接退出循环,而不再遍历后续的元素

        break

else:

    # 如果没有发现要搜索的目标,还需要一个统一的提示,

    print("没有找到 %s" % find_name)

print("循环结束")

应用场景 

在 迭代遍历 嵌套的数据类型时,例如 一个列表包含了多个字典需求:要判断 某一个字典中 是否存在 指定的 值 

  如果 存在,提示并且退出循环如果 不存在,在 循环整体结束 后,希望 得到一个统一的提示

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档