首页 > temp > python入门教程 >
-
零基础学Python:字符串及其常用方法
1.字符串
序列类型
在Python中如果我想表示字母怎么办呢?
字符串创建
字符串是 Python 中最常用的数据类型。我们可以使用引号( ' 或 " )来创建字符串。
创建字符串很简单,只要为变量分配一个值即可。
单引号和双引号
在 Python 中我们都知道单引号和双引号都可以用来表示一个字符串,比如

总体来说没有任何区别,只在单引号当普通字符时容易区分:如 var = "let's go"
三引号创建块字符串 长字符串

字符串格式化
把不是字符类型的 转变成字符串
- 在 Python 中可以使用 print 函数将信息输出到控制台
- 如果希望输出文字信息的同时,一起输出 数据,就需要使用到 格式化操作符
- % 被称为 格式化操作符,专门用于处理字符串中的格式
- 包含 % 的字符串,被称为 格式化字符串
-
% 和不同的 字符 连用,不同类型的数据 需要使用 不同的格式化字符
-
语法格式如下:
%s


format

对齐输出

f
在字符串中嵌入变量

成员运算符
in 和 not in 被称为 成员运算符
成员运算符用于 测试 序列中是否包含指定的 成员

2.字符串常用方法
字符串是不可变数据类型,所有的操作都是返回新的一个列表,不会修改原有列表
字符串 能够使用的 方法 如下:


提示:正是因为 python 内置提供的方法足够多,才使得在开发时,能够针对字符串进行更加灵活的操作!应对更多的开发需求!
查找和替换

@拓展知识
转义字符
在需要在字符中使用特殊字符时,python 用反斜杠转义字符。如下表:

原始字符串
由于字符串中的反斜线都有特殊的作用,因此当字符串中包含反斜线时,就需要使用转义字符 \ 对字符串中包含的每个 '' 进行转义。
比如说,我们要写一个关于 Windows 路径 G:\publish\codes\02\2.4 这样的字符串,如果在 Python 程序中直接这样写肯定是不行的,需要使用 \ 转义字符,对字符串中每个 '' 进行转义,即写成G:\publish\codes\02\2.4 这种形式才行。
有没有觉得这种写法很啰嗦,有没有更好的解决办法呢?答案是肯定的,借助于原始字符串可以很好地解决这个问题。
原始字符串以“r”开头,它不会把反斜线当成特殊字符。因此,上面的 Windows 路径可直接写成如下这种形式:

如何改变字符串
将下面的字符串中 world 改成 Python

字符串是一种不可变的数据类型。所有操作字符的方法都是返回一个新的字符串。可以用返回的新的字符串覆盖掉之前的字符串。
出 处:https://www.cnblogs.com/python147/p/14436093.html