python基础-字符串速查笔记

python字符串

字符串:一系列字符,用单引号或者双引号扩起

Python不支持单字符类型,单个字符也被看出作为字符串,许多用法与List一致:

访问字符串中的元素

python 复制代码
s = 'Hello World'
print(s[:5]) # Hello

s = "Hello "
t = "World"
print(s + t) # Hello World
print(s * 3) # Hello Hello Hello
print('H' in s) # True

a = 123
s = str(a)
print("type(s)", type(a)) # type(s) <class 'str'>
print("s = ", s) # s = 123

s = "Hello World"
print("len(s) =", len(s)) # len(s) = 11
print("s[2] =", s[2]) # s[2] = l
print("s[-1] =", s[-1]) # s[-1] = d
print("s[4:8] =", s[4:8]) # s[4:8] = o Wo
print("s[:5] =", s[:5]) # s[:5] = Hello
print("s[6:] =", s[6:]) # s[6:] = World
print("s[-5:] =", s[-5:]) # s[-5:] = World

转义字符

转义字符是以反斜杠()开头的特殊字符,用于表示不能直接键入的字符。

转义字符 描述
\ 续行符,在行尾
\\ 反斜杠
\' 单引号
\" 双引号
\n 换行符
\t 横向制表符
python 复制代码
s = "Hello \
World"
print(s) # Hello World

s = "Hello \" World"
print(s) # Hello " World

s = "Hello \n World"
print(s)
# Hello
# World

s = "Hello\tWorld"
print(s) # Hello    World

unicode码和字符转换

字符=>Unicode码: ord(x),x为字符,ord(x)为整数

Unicode码=>字符:chr(x),x为整数,chr(x)为字符

python 复制代码
print(ord('蓝')) # 34013
print(ord('桥')) # 26725
print(ord('a')) # 97
print(ord('b')) # 98

print(chr(34013)) # 蓝
print(chr(36725)) # 桥
print(chr(97)) # a
print(chr(98)) # b

http://www.asciima.com/ascii/12.html

字符串常用方法

字符串包含很多内置函数,合理使用相关函数可以极大提升效率

函数名 描述
isalnum() 判断字符串是否都是字母或者数字或中文字符
isalpha() 判断字符串是否都是字母或中文字符
isdigit() 判断字符串是否只包含数字
islower() 判断字符串是否全小写
isupper() 判断字符串是否全大写
isspace() 判断字符串是否只包含空白
istitle() 判断字符串是否标题化

```python s = "Hello World" # 每一个单词第一个字母都是大写,后面都是小写 print(s.istitle()) # True print(s.islower()) # False print(s.isalpha()) # False print(" \n\t ".isspace()) # True print("".isspace()) # False ``` > 转换类方法

函数名 描述
title() "标题化"的字符串
lower() 转换成小写
upper() 转换成大写
swapcase() 字符串中大写转换为小写,小写转换为大写
lstrip([chars]) 截掉字符串左边的空格或指定字符chars。
rstrip([chars]) 截掉字符串右边的空格或指定字符chars。
strip([chars]) 调用lstrip([chars])和rstrip([chars])
replace(old, new[, max]) 将字符串中的 old 替换成 new,如果 max 指定,则替换不超过 max 次
ljust(width[, fillchar]) 左对齐,并使用空格(或者fillchar)填充至指定长度width的新字符串
rjust(width[, fillchar]) 右对齐,并使用空格(或者fillchar)填充至指定长度width的新字符串
zfill(width) 右对齐,并使用0填充至指定长度width的新字符串
center(width, fillchar) 居中对齐,使用空格或者fillchar填充
python 复制代码
s = "hello world"
t = s.title()
print("s = ",s) # s = hello world
print("t = ", t) # t = Hello World

t = s.upper()
print("t = ", t)# t = HELLO WORLD

t = s.title().swapcase()
print("t = ", t) # t = hELLO wORLD

s = "    hello world"
t = s.lstrip()
print("t = ", t) # hello world

t = s.lstrip('eh ')
print("t = ", t) # llo world

s = "abcd abcd abcd abcd"
t = s.replace('a', 'A')
z = s.replace('a', 'A', 2)

print("t = ", t) # Abcd Abcd Abcd Abcd
print("z = ", z) # Abcd Abcd abcd abcd

s = "hello world"
s1 = s.rjust(30)
print(s1) #                    hello world

s2 = s.rjust(30, '_')
print(s2) # ___________________hello world

s3 = s.zfill(30)
print(s3) # 0000000000000000000hello world

查找类方法

函数名 描述
count(str, beg=0, end=len(string)) 求str在字符串中出现次数,如果指定查找范围则在[beg, end)中查找
find(str, beg=0, end=len(string)) 判断str是否在字符串中,如果指定查找范围则在[beg, end)中查找,返回找到的起始下标,不存在返回-1
rfind(str, beg=0, end=len(string)) 从右往左查找
index(str, beg=0, end=len(string)) 与find相同,只是如果str不存在,则抛出异常
rindex(str, beg=0, end=len(string)) 从右往左查找
startswith(substr, beg=0, end=len(string)) 判断是否以substr开头
endswith(suffix, beg=0, end=len(string)) 判断是否以suffix结尾
python 复制代码
s = "abcd abcd abcd abcd"
print(s.count('ac')) # 0
print(s.count('abcd')) # 4
print(s.count('abcd'),6) # 2

s = "Hello World!"
print(s.find('World')) # 6
print(s.find('world')) # -1
print(s.find('H')) # 0
print(s.find('H', 5)) # -1

字符串和List

字符串转换成list(由于字符串本身是不可修改的,转换成list可以进行修改):

python 复制代码
s = "Hello World!"
a = list(s)
print(a) # ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
print(len(a)) # 12

利用split()方法对字符串进行分割:
str.split(str="",num=string.count(str)) str表示分隔符,默认为空字符,包括空格/换行、制表符等。

num -- 分割次数,如果设置了这个参数,则最多分割成 num+1个子字符串。默认为-1,即分割所有。

python 复制代码
a = input() # 123 456
b = a.split()
print(a) # 123 456
print(b) # ['123', '456']

a = input().split() # 1 2 3 4 5 6 7 8 9 10
b = [int(x) for x in a] # 
print(b) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

map(function, sequence):把序列sequence里面的每一个元素利用function进行转化,最终结果是一个可迭代的对象,一般需要将其转换成list

python 复制代码
s = ['123', '456']
t = list(map(int, s))
print("s = ", s) # s = ['123', '456']
print("t = ", t) # [123, 456]

# 一行输入若干个数字,求数字之和
s = input().split()
a = list(map(int, s))
print(sum(a))

列表转字符串

利用str.join(seq):把序列每个元素用str连接起来

python 复制代码
s = "Hello World!"
t = list(s)
print(t)

ss = ''.join(t)
print(ss) # Hello World!
ss = '_'.join(t)
print(ss) # H_e_l_l_o_ _W_o_r_l_d_!

修改字符串

  1. 转换成List,修改后再转换成字符串
  2. 利用切片
  3. 重新赋值
  4. 利用replace函数
python 复制代码
s = "hello world"
t = list(s)
t[0] = 'H'
t = ''.join(t)
print(t) # Hello world

t = "H" + t[1:]
print(t) # Hello world

t = s.replace('h','H',1)
print(t) # Hello world

format格式化

  • Python支持格式化字符串的输出,利用format函数来调整字符串的格式。

  • Python字符串中{}表示占位符,format里面的参数将逐个放入字符串中的占位符

    • 由于format的参数要逐个放入占位符中,此时参数数量必须大于等于占位符数量
    • Python字符串中{0}{1}表示占位符,其中非负整数表示这个位置为format中的第几个参数,从0开始计数,{x}中的x不可以大于format中的参数数量
    • Python字符串中{name}、{age}表示占位符,其中name,age表示format中传递参数的参数名称,此时是根据名称来找到对应的位置,因此{}中的名称必须在format中出现
    • {}中可以加入冒号:,冒号后可以控制数字的输出格式,包括宽度、小数点等
      string --- 常见的字符串操作 --- Python 3.13.1 文档
    Type 含义
    s 字符串
    d 十进制整数
    c 十进制整数自动转换成对应的Unicode
    e或者E 科学计数法
    g或G 自动在e和f中切换
    b 十进制数转化成二进制表示输出
    o 十进制数转化成八进制表示输出
    x或者X 十进制数转化成十六进制表示输出
    f或者F 浮点数
    % 显示百分比
    数字 格式 输出 描述
    3.1415926 {} 3.1415926 原封不动输出
    3.1415926 {:.2f} 3.14 保留两位小数
    3.1415926 {:0f} 3 保留整数
    0.25 {:.2%} 25.00% 百分比输出
    25 {:0>4} 0025 0填充、右对齐、输出4位宽度
    25 {:>4} 25 空格填充、右对齐、输出4位宽度
    25 {:x<4} 25xx x填充、左对齐、输出4位宽度
    25 {:b} 11001 输出二进制
    1000000000 {:e} 1.000000e+09 科学计数法
python 复制代码
name = "zs"
age = 24
s = "大家好,我叫{},今年{}岁。".format(name,age)
print(s) # 大家好,我叫zs,今年24岁。

s = "大家好,我叫{0},今年{1}岁。 {0}:{1}".format(name,age)
print(s) # 大家好,我叫zs,今年24岁。 fzl:24

s = "大家好,我叫{name},今年{age}岁。".format(name='fzl',age=24)
print(s) # 大家好,我叫zs,今年24岁。

a = 3.1415
print("{:.2f}".format(a)) # 3.14

补充:格式化字符串的其他方法
python格式化字符串的三种方法(%,format,f-string)_在java中可以使用string.format函数,python中可以使用%或format方法来格式-CSDN博客

相关推荐
一只积极向上的小咸鱼几秒前
PyTorch 和 Python关系
人工智能·pytorch·python
m0_7482550223 分钟前
python的sql解析库-sqlparse
数据库·python·sql
zhu_superman36 分钟前
c语言中的未定义行为
c语言·开发语言
小爬虫程序猿37 分钟前
衣联网的商品列表页面结构是怎样的?
开发语言·爬虫·python
孔令飞1 小时前
18 | 实现简洁架构的 Handler 层
开发语言·ai·云原生·golang·kubernetes
成风6931 小时前
c++比较与对比动态内存分配和回收运算符new,new[],delete,delete[]。
开发语言·c++
咩咩觉主1 小时前
C# &Unity 唐老狮 No.8 模拟面试题
开发语言·unity·c#
四念处茫茫1 小时前
【C语言系列】字符函数和字符串函数
c语言·开发语言·visual studio
dlhto1 小时前
Ollama+ WebUI 部署deepseek-r1
linux·python·语言模型
PfCoder1 小时前
C#结构体(Struct)详解
开发语言·c#·visual studio