在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 之字符串的使用的更多相关文章

  1. Python格式化字符串~转

    Python格式化字符串 在编写程序的过程中,经常需要进行格式化输出,每次用每次查.干脆就在这里整理一下,以便索引. 格式化操作符(%) "%"是Python风格的字符串格式化操作 ...

  2. python学习--字符串

    python的字符串类型为str 定义字符串可以用 ‘abc' , "abc", '''abc''' 查看str的帮助 在python提示符里 help(str) python基于 ...

  3. Python格式化字符串和转义字符

    地址:http://blog.chinaunix.net/uid-20794157-id-3038417.html Python格式化字符串的替代符以及含义     符   号     说     明 ...

  4. [转载] python 计算字符串长度

    本文转载自: http://www.sharejs.com/codes/python/4843 python 计算字符串长度,一个中文算两个字符,先转换成utf8,然后通过计算utf8的长度和len函 ...

  5. Python基础-字符串格式化_百分号方式_format方式

    Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存.[PEP-3101] This ...

  6. python判断字符串

    python判断字符串 s为字符串s.isalnum() 所有字符都是数字或者字母s.isalpha() 所有字符都是字母s.isdigit() 所有字符都是数字s.islower() 所有字符都是小 ...

  7. Python格式化字符串

    在编写程序的过程中,经常需要进行格式化输出,每次用每次查.干脆就在这里整理一下,以便索引. 格式化操作符(%) "%"是Python风格的字符串格式化操作符,非常类似C语言里的pr ...

  8. python(七)字符串格式化、生成器与迭代器

    字符串格式化 Python的字符串格式化有两种方式:百分号方式.format方式 1.百分号的方式 %[(name)][flags][width].[precision]typecode (name) ...

  9. Python 的字符串格式化和颜色控制

    (部分内容源自武神博客和网络收集.) Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两 ...

  10. python反转字符串(简单方法)及简单的文件操作示例

    Python反转字符串的最简单方法是用切片: >>> a=' >>> print a[::-1] 654321 切片介绍:切片操作符中的第一个数(冒号之前)表示切片 ...

随机推荐

  1. ASP.NET Core GRPC 和 Dubbo 互通

    一.前言 Dubbo 是比较流行的服务治理框架,国内不少大厂都在使用.以前的 Dubbo 使用的是私有协议,采集用的 hessian 序列化,对于多语言生态来说是极度的不友好.现在 Dubbo 发布了 ...

  2. 基于QT和C++实现的翻金币游戏

    基于QT和C++的翻金币游戏 声明: QT翻金币项目可以说是每个新学QT的同学都会去写的一个项目,网上的源码也很多,我也是最近刚开始学QT,所以也参考了很多前辈的代码自己重新敲了一遍代码. 游戏介绍: ...

  3. 通过QQ抓IP查询地址

    使用工具: Wireshark 可以直接搜索官网获取,个人用的免费的,也可以直接在kali中也是可以直接用的.这里就不介绍怎么安装了,网上很多. 步入正题: 通过wireshark进行抓包查地址,需要 ...

  4. List接口中的常用方法

    void add(int index, Object ele):在index位置插入ele元素boolean addAll(int index, Collection eles):从index位置开始 ...

  5. VScode将代码提交到远程服务器、同时解决每次提交都要输入密码的问题(这里以gitee为例子)

    文章目录 1.第一种情况.项目直接从gitee上拉取下来 2.第二种情况.将新建的项目提交到远程服务器 3.解决将代码提交到远程每次都要输入用户名和密码 4.个人遇到的奇葩问题 1.第一种情况.项目直 ...

  6. Python爬虫urllib库的使用

    urllib 在Python2中,有urllib和urllib2两个库实现请求发送,在Python3中,统一为urllib,是Python内置的HTTP请求库 request:最基本的HTTP请求模块 ...

  7. 17_Vue列表过滤_js模糊查询

    列表过滤 需求分析 这里呢有张列表,假设这个列表有一百多条数据 当我在这个 搜索框当中 搜索 单个关键字的时候 (冬,周,伦),它能把带了这几个关键字的信息都给我罗列出来 === 跟数据库的 模糊查询 ...

  8. Microsoft Office for Mac最新版本安装教程,亲测可用!!!

    办公必备的Office工具,它为需要使用 Office 工具的用户和企业设计,让他们可以利用功能强大的 Outlook 来处理电子邮件.日历和通讯录事宜.你所熟知和信赖的 Office 经过更新后,可 ...

  9. 恭喜磊哥喜提n+1

    昨天下午两点多磊哥突然喊我下楼,第一反应是"这孙子,抽烟就直说,还说个事,你以外你是吉祥村大姐啊". 心里骂完以后我慢慢悠悠下楼了,见他在打电话我先默默点上一支,准备待他结束以后对 ...

  10. 在ubuntu 上安装golang

    https://golang.google.cn/dl/ 方式一 下载安装包 wget https://golang.google.cn/dl/go1.19.linux-amd64.tar.gz 解压 ...