Python学习笔记——字符串

这篇博客详细介绍了Python字符串的使用,包括索引、切片、删除、转义、raw字符串及各种字符串运算,如连接和重复。还探讨了Unicode字符串以及内建函数如ord()、chr()、str()、len()、min()和max()在处理字符串时的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 索引

字符串内的字符通过索引来访问

索引也成为下标

字符索引不能越界

>>> a= 'afe'
>>> a
'afe'
>>> a[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

2 切片

s[起始索引:结束索引:步长]

含起始,不含结束值
这里写图片描述

>>> a = 'hello'
>>> a[1:4]
'ell'
>>> a[1:]
'ello'
>>> a[:4]
'hell'
>>> a[:]
'hello'
>>> a[-1:-4]
''
>>> a[-1:-4:1]
''
>>> a[-1:-4:-1]
'oll'
>>> a[1:4:1]
'ell'
>>> a[1:4:-1]
''
>>> a[4:1:1]
''
>>> a[4:1:-1]
'oll'
>>> a[::2]
'hlo'
>>> a[::-2]
'olh'

3 删除字符串

del str

str = 'abcd'
del str

4 字符串转义

\(在尾行时) 续行符
\\        反斜杠
\'        单引号  
\"        双引号   
\O\n        换行    
\r        回车     

5 raw字符串

r"字符串"
r'字符串'

该表达形式可以使转义字符失效
但对三引号字符串不起作用

print('\n')
print(r'\n')
r'\n\rafaiogha'

6 字符串运算

6.1 字符串连接

”+“

>>> a = "123"
>>> b = "456"
>>>> "123""456"
'123456'
>>> ab
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ab' is not defined
>>> a+b
'123456'

注意:
两个或多个字符串(封闭的引号隔开)相邻时,则自动链接成一个字符串。
与用加号“+”效果一样。

6.2 重复输出字符串

”*“

>>> m = "abc"
>>> m*2
'abcabc'
>>> m*3
'abcabcabc'

6.3 成员运算符

>>> "a" in "abc"
True
>>> "1" not in "234"
True

in 如果字符串中包括有给定的字符串,则返回True

not in 如果字符串中不包括给你的字符串时返回True

7 Unicode字符串

.py文件中显示指定utf-8编码

#!/usr/bin/env python3
#-*- coding:utf-8 -*-

8 内建函数处理字符串

8.1 ord函数

得到一个字符的ASCII值

ord(单个字符的字符串)

错误的写法

>>> ord(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 3 found
>>> ord('ab')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found

正确的写法

>>> ord('a')
97
>>> ord('1')
49

8.2 chr函数

得到数字对应的ASCII字符

>>> chr(97)
'a'
>>> chr(1)
'\x01'
>>> chr(49)
'1'

8.3 str函数

将对象转换成合理的字符串

>>> str(12)
'12'
>>> str('abc')
'abc'
>>> str(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'l' is not defined
>>> str(abc)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'abc' is not defined

8.4 len()函数

获得字符串长度

8.5 min()函数

获得字符串中最小值

>>> min('abc')
'a'

8.6 max()函数

获得字符串中最大值

>>> max('abc')
'c'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值