Python 高级数据类型之字符串(string)

以下是本人最近学习字符串的相关说明及代码分享。

字符串的定义

  • 字符串 就是 一串字符,是编程语言中表示文本的数据类型
  • 在Python中可以使用一对双引号" 或者一对单引号 ’ 定义一个字符串
    • 虽然可以使用 " 或 ’ 做字符串的转义,但是实际开发中:
      • 如果字符串内部需要使用 " ,可以使用 ’ 定义字符串
      • 如果字符串内部需要使用 ’ ,可以使用 " 定义字符串
  • 也可以使用索引获取一个字符串中指定位置的字符,索引计数从 0 开始
  • 也可以使用 for 循环遍历字符串中的每个字符
string_14_字符串定义和遍历

代码

str1 = "hello python"
str2 = '我的外号是"小西瓜"'
print(str2)
print(str1[6])

for c in str1:
    print(c, end=" ")

输出结果

我的外号是"小西瓜"
p
h e l l o p y t h o n

string_15_字符串统计操作

代码

hello_str = "hello python"

# 1.统计字符串长度
print(len(hello_str))

# 2.统计某个子字符串出现的次数
print(hello_str.count("h"))
print(hello_str.count("d"))

# 3.某个子字符串出现的位置
print(hello_str.index("p"))
# 注意,如果使用index方法传递的子字符串不存在,程序会报错 ValueError: substring not found
print(hello_str.index("d"))

输出结果

12
2
0
6
Traceback (most recent call last):
File “D:/PycharmProjects/05_高级数据类型/string_15_字符串统计操作.py”, line 13, in
print(hello_str.index(“d”))
ValueError: substring not found

字符串常用操作方法
在ipython3中定义一个字符串 hello_str = “”
输入hello_str. 按下Tab键,ipython会提示列表能够使用的方法如下:

capitalize()  encode()  format()  isalpha()  isidentifier() isspace() ljust()  partition()  rjust()  split()  swapcase()  zfill()  
casefold()  endswith()  format_map()  isascii()  islower()  istitle()  lower()  replace()  rpartition()  splitlines()  title()  
center()  expandtabs()  index()  isdecimal()  isnumeric()  isupper()  lstrip()  rfind()  rsplit()  startswith()  translate()
count()  find()  isalnum()  isdigit()  isprintable()  join()  maketrans()  rindex()  rstrip()  strip()  upper()  

判断类型(9)

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

代码

# 1.判断空白字符
space_str = " \t\r\n"
print(space_str.isspace())

# 2.判断字符串中是否只包含数字,
# >1、都不能判断小数
# num_str = "1.1"
# >2、unicode字符串
# num_str = "⑴"
# num_str = "\u00b2"
# >3、中文数字
num_str = "一千零一"
print(num_str)
print(num_str.isdecimal())
print(num_str.isdigit())
print(num_str.isnumeric())

输出结果

True
一千零一
False
False
True

查找和替换(7)

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

代码

hello_str = "Hello Python"
# 1.判断是否以指定字符串开头
print(hello_str.startswith("Hello"))
print(hello_str.startswith("hello"))
# 2.判断是否以指定字符串结尾
print(hello_str.endswith("Python"))
print(hello_str.endswith("python"))
# 3.查找指定字符串
# index方法同样可以查询子字符串在字符串中的索引,如果不存在会报错 ValueError: substring not found
print(hello_str.find("Python"))
print(hello_str.find("World"))
# print(hello_str.index("World"))
# 4.替换字符串
# replace方法执行完成后会返回一个新的字符串(注意:不会修改原有字符串的内容)
print(hello_str.replace("Python", "World"))
print(hello_str)

输出结果

True
False
True
False
6
-1
Hello World
Hello Python

大小写转换(5)

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

文本对齐(3)

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

去除空白字符(3)

方法说明
string.lstrip(width)截掉string左边(开始)的空白字符
string.rstrip(width)截掉string右边(开始)的空白字符
string.strip(width)截掉string左右两边的空白字符
string_18_字符串文本对齐、去除空白字符

代码

# 假设:以下内容从网络抓取
# 要求:按顺序且居中对齐输出以下内容
# ljust 左对齐 rjust 右对齐
poem = ["登鹳雀楼", "王之涣", "白日依山尽", "黄河入海流", "欲穷千里目", "更上一层楼"]
for poem_str in poem:
    print("|%s|" % poem_str.center(10, " "))

print()
# 若抓取的内容存在空白字符以及tab、换行、回车等特殊字符,需要先进行处理再展示
poem1 = ["\t\n登鹳雀楼", "王之涣", "白日依山尽\t\n\r", "黄河入海流", "欲穷千里目", "更上一层楼"]
for poem1_str in poem1:
    # 先使用strip方法去除空白字符
    # 再使用center方法居中显示
    print("|%s|" % poem1_str.strip().center(10, " "))


输出结果

|   登鹳雀楼   |
|   王之涣    |
|  白日依山尽   |
|  黄河入海流   |
|  欲穷千里目   |
|  更上一层楼   |

|   登鹳雀楼   |
|   王之涣    |
|  白日依山尽   |
|  黄河入海流   |
|  欲穷千里目   |
|  更上一层楼   |

拆分和连接(5)

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

代码

# 假设:以下内容从网络抓取
# 要求:
# 1、将字符串中的空白字符去掉
# 2、在使用" "作为分隔符,拼接成一个整齐的字符串
poem_str = "登鹳雀楼\t\t王之涣\n白日依山尽\t黄河入海流\n欲穷千里目 更上一层楼"

print(poem_str)
# 1.拆分字符串
poem_list = poem_str.split()
print(poem_list)
# 2.合并字符串
result_str = " ".join(poem_list)
print(result_str)

输出结果

登鹳雀楼 王之涣
白日依山尽 黄河入海流
欲穷千里目 更上一层楼
[‘登鹳雀楼’, ‘王之涣’, ‘白日依山尽’, ‘黄河入海流’, ‘欲穷千里目’, ‘更上一层楼’]
登鹳雀楼 王之涣 白日依山尽 黄河入海流 欲穷千里目 更上一层楼

字符串的切片

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

切片的语法:

字符串[开始索引:结束索引:步长]
字符串切片演练代码
num_str = "0123456789"
# 1.截取2-5位置的字符串
print(num_str[2:6])
# 2.截取从2-末尾的字符串
print(num_str[2:])
# 3.截取从开始-5 位置的字符串
print(num_str[0:6])
print(num_str[:6])
# 4.截取完整的字符串
print(num_str[:])
# 5.从开始位置,每隔一个字符截取字符串
print(num_str[::2])
# 6.从索引1开始,每隔一个取一个
print(num_str[1::2])
# 7.截取从2 - 末尾-1  的字符串
print(num_str[2:-1])
# 8.截取字符串末尾两个字符
print(num_str[-2:])
# 9.字符串的逆序(面试题)
print(num_str[-1::-1])
print(num_str[::-1])

输出结果

2345
23456789
012345
012345
0123456789
02468
13579
2345678
89
9876543210

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值