python中的字符串
创建一个字符串,就是将字符放入单引号 双引号 或者三引号中如:
1
2
3
a = "Hellow world";
b = 'python is good';
c = """Welcome'you'to visit the blog"""
三引号作用:里面可以放入单引号或者双引号
字符串存储 以0开始要提取字符串中的字符 则可使用索引运算符s:
1
2
3
a= 'hellow world ';
b = a
print(b);
输出结果:
o
要提取一个子字符串,可以使用切片运算符s这会提取 字符串s中索引位置K处的所有字符,其中索引为K范围是i<=k<j 如果省略i 则假定使用字符串起始位置 如果省略j则假定使用字符串结尾位置
1
c = a[:5] #始位置位置0开始 提取5个字符
输出结果:
hellow
1
d = a #从位置序列5 开始提取到结尾
输出结果:
wworld
1
e = a#索引位置3 开始提取到索引位置7的位置
输出结果
lowwo
可以使用+(连接运算符)连接两个字符串
1
g = a + ' This istest';
输出结果:
hellowworld this is a test
python+始终会连接字符串
1
2
3
x = '37';
y = '42';
z = x+y#字符串连接
输出结果:
3742
如果要执行数学计算使用int 或者float 函数将字符串转换成数值:
1
z= int(x)+int(y);
输出结果:
z = 79#(Integer +)
使用 strrepr或者format函数 可将非字符串值转换成字符串类型值
1
2
3
s = "the value of x is "+ str(z);
s = "the value of x is" +repr(z);
s = "the value of x is" + format(x)
如果不使用以上函数转换 则会报错
以上代码如果输出(类型):
"the value of x is83 "class 'int'>
"the value of x is83"<class 'str'>
"the value of x is83"class 'str'>
注意 在使用 repr时 会出现不精确的问题 这是双精度浮点数的一个特点 :底层地算计硬件无法精确表示十进制小数,并不是python的bug
与PHP之间的比较:
1,php中字符串是用‘str’“str” 单引号或者双引号
2,php中字符串也有索引值 如:
1
2
$str = 'this is demo';
echo $str;
输出结果:
i
3,PHP中会把字符串中的数字 解释为数值型数据 如:
1
2
3
$i = '7';
$j = '8';
echo $i+$j;
输出结果:
15
4,php中 字符串不能与数字直接连接 需要使用变量接收值后变量之间使用连接运算符.连接 不需要转换数据类型 如:
1
2
3
$number= 5;
$demo = 'this is int and string'.$number;
echo $demo;
输出结果:
'this is int and string5
总结:
1,如何创建字符串 :单引 双引 三引
2,字符串中的字符索引s切片索引s 范围:i<=k<j
3,+ 连接运算 始终会连接字符串 如‘3'+'7' = 37
4,int,float,str,repr,format等函数转换数字为字符串
页:
[1]