当前位置: 首页 > news >正文

python基础-字符串速查笔记

python字符串

字符串:一系列字符,用单引号或者双引号扩起
Python不支持单字符类型,单个字符也被看出作为字符串,许多用法与List一致:

访问字符串中的元素

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横向制表符
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)为字符

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填充
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结尾
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可以进行修改):

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,即分割所有。

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

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连接起来

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函数
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}00250填充、右对齐、输出4位宽度
    25{:>4}25空格填充、右对齐、输出4位宽度
    25{:x<4}25xxx填充、左对齐、输出4位宽度
    25{:b}11001输出二进制
    1000000000{:e}1.000000e+09科学计数法
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博客

相关文章:

  • vscode arm拓展 keil acm5 到acm6迁移
  • HarmonyOS Next 中的状态管理
  • 基础玩转物联网-4G模块如何快速实现与MQTT服务器通信
  • Goland如何玩依赖注入——基于gone@v2创建一个service
  • 2025-03-10 学习记录--C/C++-C语言 易错点 大总结
  • 【leetcode hot 100 2】两数相加
  • Git 设置全局代理
  • 第3节:IP地址分类与子网划分实战指南
  • 『PostgreSQL』PGSQL备份与还原实操指南
  • MySQL的约束
  • 学习笔记12——并发编程之线程之间协作方式
  • rust语言match模式匹配涉及转移所有权Error Case
  • Java本地方法根据线上地址下载图片到本地然后返回本地可以访问的地址
  • 【氮化镓】开态GaN HEMTs中氧诱导Vth漂移的缺陷演化
  • 力扣:找到一个数字的 K 美丽值(C++)
  • 面试题之强缓存协商缓存
  • javascript-es6 (六)
  • 从机器学习到生成式AI狂潮:AWS的AI征程从未停息
  • 【实战ES】实战 Elasticsearch:快速上手与深度实践-7.2.2自动扩缩容策略(基于HPA)
  • 2025年总结zabbix手动部署过程!
  • 海外考古大家访谈|冈村秀典:礼制的形成与早期中国
  • 北方将现今年首场大范围高温天气,山西河南山东陕西局地可超40℃
  • 上海黄浦江挡潮闸工程建设指挥部成立,组成人员名单公布
  • 美国与卡塔尔签署超2435亿美元经济及军事合作协议
  • 马上评|“衣服越来越难买”,对市场是一个提醒
  • 马上评|“为偶像正名”的正确做法是什么