python 之字符串的使用
在python中,字符串是最常用的数据类型,通常由单引号(' ')、双引号(" ")、三重引号(''' ''',""" """)引起来。
# 字符串的创建
str1 = "hello world"
str2 = 'sunlight'
str3 = '''On a new day,
the sun rises in the East
'''
str4 = """On a new day,
the sun rises in the East"""
str5 = "What's this?"
使用单引号、双引号、三重引号创建的字符串是无区别的,验证如下
str1 = 'sunlight'
str2 = "sunlight"
str3 = """sunlight"""
str4 = '''sunlight'''
print(str1 == str2 == str3 == str4) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
True Process finished with exit code 0
三重引号的使用场景一般用于类、函数等注释,或者定义含有多行的字符串
字符串是一个由独立字符组成的序列,意味着可以
1.获取字符串长度
# 获取字符串长度
str1 = 'sunlight'
print(len(str1)) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
8 Process finished with exit code 0
2、通过下标读取其中的某个字符
# 通过下标读取字符
str1 = 'sunlight'
print(str1[1])
print(str1[0])
print(str1[-1]) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
u
s
t Process finished with exit code 0
3、通过切片方式读取字符串片段
# 切片方式读取片段
str1 = 'sunlight'
print(str1[2:4])
print(str1[-4:-1]) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
nl
igh
4.字符串拼接
# 字符串拼接
str1 = 'sunlight'
str2 = 'hello ' print(str2 + str1)
print(str1[2:4] + str2[1:3]) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
hello sunlight
nlel
5.遍历字符串
# 遍历字符串
str1 = 'sunlight'
for i in str1:
print(i) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
s
u
n
l
i
g
h
t Process finished with exit code 0
python中的转义字符:就是用反斜杠开头的字符串,表示特定的意义,常见的转义字符如表中所示

# 转义示例
str4 = """On a new day,the sun rises in the East"""
str5 = 'what\t do\b you \v do'
str6 = 'What\'s this?'
str7 = "It's \"cat\""
print(str4, "\n", str5, "\n", str6, "\n", str7) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
On a new day,the sun rises in the East
what d you do
What's this?
It's "cat" Process finished with exit code 0
python中字符串常用的运算符

# 运算符示例
str1 = 'sun' + 'light '
s = "r" in str1
t = "r" not in str1
w = r'\n' + R'\t'
z = 3.14159 print(str1, str1*3 + "\n", s, t, "\n" + w)
print("Π的值是%s:" % z) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
sunlight sunlight sunlight sunlight
False True
\n\t
Π的值是3.14159: Process finished with exit code 0
改变字符串:
在数组中可以通过下标直接更改值,但是字符串中同样的操作会提示“'str' object does not support item assignment”
# 变更字符串
str1 = 'sunlight'
str1[0] = "D"
print(str) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
Traceback (most recent call last):
File "D:/demo/str_1.py", line 52, in <module>
str1[0] = "D"
TypeError: 'str' object does not support item assignment Process finished with exit code 1
通过创建新的字符串间接更改
# 创建新的字符串间接更改
str1 = 'sunlight'
s = "S" + str1[1:]
t = str1.replace("s", "S")
str1 = s
print(str1, t) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
Sunlight Sunlight Process finished with exit code 0
通过符号 += 更改
# 通过 += 符号 更改
str1 = 'sun'
str1 += 'light'
print(str1) info = "start "
for s in str1:
info += s
print(info) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
sunlight
start sunlight Process finished with exit code 0
python中的字符串格式化
字符串格式化可以理解为将实际值插入模板中
# 使用%实现字符串格式化
student = {"张三": 19, "李四": 20, "王五": 20}
for info in student:
print("学生 %s的年龄为 %s" % (info, student[info])) # 使用string.format()方法实现字符串格式化
prices = {"apple": 8.99, "banana": 6.99, "orange": 7.99}
for price in prices:
print("水果 {}的单价为 {}".format(price, prices[price])) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
学生 张三的年龄为 19
学生 李四的年龄为 20
学生 王五的年龄为 20
水果 apple的单价为 8.99
水果 banana的单价为 6.99
水果 orange的单价为 7.99 Process finished with exit code 0
常用字符串内建函数
string.split(sep, maxsplit):maxsplit给定值max,sep在字符串中出现的次数为num, 且给定的值0<= max <=num,以sep作为分隔符进行切片字符串,则分割max+1个字符串,若max不传(不传时默认为-1)或者传入的值大于num,则默认分割num+1个字符串,并返回由字符串组成的数组
str1 = 'sunlight'
r = str1.split("l") # maxsplit不传时,默认为-1,返回1+1个字符
s = str1.split("l", 0) # maxsplit传入0则返回0+1个字符
t = str1.split("l", 3) # maxsplit传入值大于分隔符出现的次数,返回1+1个字符
w = str1.split() # sep 不传时,默认为空白字符
print(r, "\n", s, "\n", t, "\n", w) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
['sun', 'ight']
['sunlight']
['sun', 'ight']
['sunlight'] Process finished with exit code 0
string.strip(chars): 从起始至末尾去掉指定的chars,若不指定默认去除字符串左边空格和末尾空格(相当于执行了string.lstrip()和string.rstrip()),并返回去除后的字符串
# 常用内建函数
str1 = ' sunlight '
t = str1.strip()
w = str1.strip("t ")
print(t)
print(str1)
print(w) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
sunlight
sunlight
sunligh Process finished with exit code 0
string.rstrip(chars): 右起去掉指定的chars,若不指定默认去除字符串末尾空格,并返回去除后的字符串
# 常用内建函数
str1 = ' sunlight '
x = str1.rstrip()
y = str1.rstrip("t ")
print(str1)
print(x)
print(y) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
sunlight
sunlight
sunligh Process finished with exit code 0
string.lstrip(chars): 左起删除指定的chars,若不指定默认去除字符串左边空格,并返回去除后的字符串
# 常用内建函数
str1 = ' sunlight '
z = str1.lstrip()
t = str1.lstrip(' su')
print(z)
print(t) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
sunlight
nlight Process finished with exit code 0
string.find(sub, start, end):检测字符串中是否包含指定字符串sub,如果包含则返回首次出现的位置索引值,否则返回-1,start、end非必填,若指定start、end则在指定范围内查找
# 常用内建函数
str1 = 'sunlightn'
a = str1.find("n") # 字符串中含有n,返回首次出现的位置索引值2
b = str1.find("n", 3) # 从索引为3开始检测,返回首次出现的位置索引值8
c = str1.find("n", 0, 2) # 从索引[0, 2)开始检测,检测不到返回-1
print(a, b, c) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
2 8 -1 Process finished with exit code 0
string.rfind(sub, start, end):用法与find类似,区别在返回指定sub最后出现的位置索引值,否则返回-1
# 常用内建函数
str1 = 'sunlightn'
e = str1.rfind("n") # 字符串中含有n,返回最后出现的位置索引值8
f = str1.rfind("n", 0, 3) # 从索引[0, 3)开始检测
print(e, f) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
8 2 Process finished with exit code 0
string.count(sub, start, end):返回指定sub在字符串中出现的次数,若指定start、end则在指定范围内统计
# 常用内建函数
str1 = ' sunlight '
j = str1.count(" ")
k = str1.count(" ", 2, 9)
print(j, k) "D:\Program Files\Python\Python37-32\python.exe" D:/demo/str_1.py
5 2 Process finished with exit code 0
python 之字符串的使用的更多相关文章
- Python格式化字符串~转
Python格式化字符串 在编写程序的过程中,经常需要进行格式化输出,每次用每次查.干脆就在这里整理一下,以便索引. 格式化操作符(%) "%"是Python风格的字符串格式化操作 ...
- python学习--字符串
python的字符串类型为str 定义字符串可以用 ‘abc' , "abc", '''abc''' 查看str的帮助 在python提示符里 help(str) python基于 ...
- Python格式化字符串和转义字符
地址:http://blog.chinaunix.net/uid-20794157-id-3038417.html Python格式化字符串的替代符以及含义 符 号 说 明 ...
- [转载] python 计算字符串长度
本文转载自: http://www.sharejs.com/codes/python/4843 python 计算字符串长度,一个中文算两个字符,先转换成utf8,然后通过计算utf8的长度和len函 ...
- Python基础-字符串格式化_百分号方式_format方式
Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存.[PEP-3101] This ...
- python判断字符串
python判断字符串 s为字符串s.isalnum() 所有字符都是数字或者字母s.isalpha() 所有字符都是字母s.isdigit() 所有字符都是数字s.islower() 所有字符都是小 ...
- Python格式化字符串
在编写程序的过程中,经常需要进行格式化输出,每次用每次查.干脆就在这里整理一下,以便索引. 格式化操作符(%) "%"是Python风格的字符串格式化操作符,非常类似C语言里的pr ...
- python(七)字符串格式化、生成器与迭代器
字符串格式化 Python的字符串格式化有两种方式:百分号方式.format方式 1.百分号的方式 %[(name)][flags][width].[precision]typecode (name) ...
- Python 的字符串格式化和颜色控制
(部分内容源自武神博客和网络收集.) Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两 ...
- python反转字符串(简单方法)及简单的文件操作示例
Python反转字符串的最简单方法是用切片: >>> a=' >>> print a[::-1] 654321 切片介绍:切片操作符中的第一个数(冒号之前)表示切片 ...
随机推荐
- Java 泛型程序设计
1. 泛型类 public class Pair<T> { private T first; private T second; public void setSecond(T seco ...
- 【LeetCode第 313 场周赛】忘光光
比赛链接 最近不怎么打比赛,不能马上反应过来考察的是什么,全部忘光光了... 6192. 公因子的数目 题意: 给定 \(a\) 和 \(b\),问两者的公因子数量 数据范围:\(1\leq a,b\ ...
- Go实现优雅关机与平滑重启
前言 优雅关机就是服务端关机命令发出后不是立即关机,而是等待当前还在处理的请求全部处理完毕后再退出程序,是一种对客户端友好的关机方式.而执行Ctrl+C关闭服务端时,会强制结束进程导致正在访问的请求出 ...
- Hbase创建表参数说明
Hbase创建表操作及参数说明 1.创建命名空间 create_namespace 'test' 2.创建user表,列族:info create 'test:user', 'info' 3.查看表结 ...
- .net core -利用 BsonDocumentProjectionDefinition 和Lookup 进行 join 关联 MongoDB 查询
前序 前段时间由于项目需要用到MongoDB,但是MongoDB不建议Collection join 查询,网上很多例子查询都是基于linq 进行关联查询.但是在stackoverflow找到一个例 ...
- 7.websocket收发消息
客户端主动向服务端发起websocket连接,服务端接收到连接后通过(握手) 客户端 websocket socket = new WebSocket('ws://127.0.0.1/ws/'); 服 ...
- 这次彻底读透 Redis
1. Redis 管道 我们通常使用 Redis 的方式是,发送命令,命令排队,Redis 执行,然后返回结果,这个过程称为Round trip time(简称RTT, 往返时间).但是如果有多条命令 ...
- VS使用正则表达式删除程序中的空行
Ctrl+H; 需要替换的正则表达式 ^(?([^\r\n])\s)*\r?$\r?\n
- ES6学习笔记(十四)module的简单使用
1.前言 module模块机制是es6新引入的,它解决了作用域的问题,使代码更加规范和结构化. 下面简单的使用一下. 2.基本使用 2.1 模块和脚本的区别 模块代码运行在严格模式下,并且没有任何办法 ...
- Day03.2:Java的基础语法
Java基础语法 注释 (注释不会被运行,仅仅作为解释或笔记提供给作者帮助回忆) 单行注释格式:// 多行注释格式: /**/ 文档注释格式:/** */ 示例图 标识符 概念:所有的组成部分都需要名 ...