栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python入门:字符串

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python入门:字符串

所有标准序列操作(索引、切片、乘法、成员检查、长度、最小值、最大值)都适用于字符串,但是字符串是不可变的,因此所有的元素赋值和切片赋值都是非法的。

1="font-family: 微软雅黑, 'Microsoft YaHei';">a 'http://www.python.org'
a[-3:]='com'
Traceback (most recent call last):
  File "", line 1in 
    a[-3:]='com'
TypeError: 'str' object does not support item assignment
</span>

python提供了多种字符串设置方法,以前,主要的解决方法是使用字符串格式设置运算符-百分号。这个运算符的行为类似C语言中的景点函数printf:在%左边制定一个字符串,并在右边指定要设置其格式的值。指定要设置其格式的值,可使用单个值,可使用元组或字典。

1="font-family: 微软雅黑, 'Microsoft YaHei';">format='http:// %s.%s.org'
values('www','python')
format values
'http:// www.python.org'
</span>

上述%s称为转换说明符,指出了要将值插入的地方,s意味着将值视为字符串进行格式设置。如果指定的不是字符串,将使用str将其转换为字符串,其他说明符将导致其他转换形式。

常用的另一种方式

1="font-family: 微软雅黑, 'Microsoft YaHei';">"{},{},and {}".format("first","second","third")
'first,second,and third'
 "{1},{0},{3},{2}".format("first","second","third","four")
'second,first,four,third'
 "{0},{1},{2},{3}".format("first","second","third","four")
'first,second,third,four'
</span>
1="font-family: 微软雅黑, 'Microsoft YaHei';"># 调用math中的pi模块
from math import pi
"{name} is approximately {value:.3f}.".format(value=pi,name="π")                            
'π is approximately 3.142.'

这里value:.3f制定了格式说明符,意味着使用3位小数的浮点数格式。

如果变量与替换字段同名,可使用

1="font-family: 微软雅黑, 'Microsoft YaHei';">from math import e
 f"Euler's constant is roughly {e}."                          
"Euler's constant is roughly 2.718281828459045."
同比:
"Euler's constant is roughly {e}.".format(e=e)
"Euler's constant is roughly 2.718281828459045."
</span>

设置字符串格式

组成部分:字段名、转换标志、格式说明符。

字段名:索引或标识符,指出要设置那个值的格式并使用结果来替换该字段。除指定值外,还可指定值的特定部分,如元素。

转化标志:跟在叹号后面的单个字符,当前支持字符包括r(repr)、s(str)、a(ascii)。如果制定了转换标志,将不适用对象本身的格式设置机制,而是使用指定的函数将对象转换为字符串,在做进一步的格式设置。

格式说明符:跟在冒号后面的表达式,格式说明符让我们能够详细地制定最终的格式,包括格式类型(如字符串,浮点数或十六进制)。

替换字段名

1="font-family: 微软雅黑, 'Microsoft YaHei';">"{} {} {} {}".format(1,2,3,4)                            
'1 2 3 4'
#通过索引来指定那个字段中对应的未命名参数。
"{0} {3} {1} {2}".format(1,2,3,4)                          
'1 4 2 3'

基本转换

1="font-family: 微软雅黑, 'Microsoft YaHei';">print("{pi!s} {pi!r} {pi!a}".format(pi="π"))  
π 'π' 'u03c0'
</span>

分别使用str、repr、ascii进行转换

还可以指定转换值的类型

1="font-family: 微软雅黑, 'Microsoft YaHei';""The number is {}".format(42)    
'The number is 42'
"The number is {:f}".format(42)   
'The number is 42.000000'
</span>

或二进制格式

1="font-family: 微软雅黑, 'Microsoft YaHei';">"The number is {:b}".format(42)    
'The number is 101010'
</span>

字符串格式设置类型说明符

整型:

  •  b 二进制

  • c 字符型,把数字转成表示unicode的字符

  • d 十进制

  • o 八进制

  • x 十六进制,显示小写字母

  • X 十六进制,显示大写字母

  • n 与d行为相同,使用本地的数字表示方式

  • ''(空,没有空格) 与d相同

浮点数

  • e 科学计数法表示,小写e

  • E 科学计数法表示,大写E

  • f 显示为定点数,默认小数点后六位

  • F 同f

  • g 自动选择是否用科学记数法表示

  • G 同g

  • n 同g,使用本地表示方式

  • % 使用百分比表示

  • ''(空) 同g


宽度、精度、和千位符

1="font-family: 微软雅黑, 'Microsoft YaHei';""{number:10}".format(number=3)      
'         3'
"{name:10}".format(name="andy")      
'andy 
 "Pi day is {pi:10.3f}".format(pi=pi)      
'Pi day is      3.142'     '
# 或千位符
"This is {:,}".format(10**10)   
'This is 10,000,000,000'

符号、对齐及填充

1="font-family: 微软雅黑, 'Microsoft YaHei';"'{:010.2f}'.format(pi)  
'0000003.14'
print('{0:<10.2f}n{0:>10.2f}n{0:^10.2f}'.format(pi))      
3.14      
      3.14
   3.14
# 可以制定字符作为填充字符 
"{:$^15}".format(" hello ")
'$$$$ hello $$$$'

print('{0:10.2f}n{1:10.2f}'.format(pi,-pi))
     3.14
    -3.14
 
print('{0:10.2f}n{1:=10.2f}'.format(pi,-pi))
     3.14
-     3.14

print('{0:-.2f}n{1:-.2f}'.format(pi,-pi))
3.14
-3.14

print('{0:+.2f}n{1:+.2f}'.format(pi,-pi))
+3.14
-3.14

print('{0:+10.2f}n{1:+10.2f}'.format(pi,-pi))
    +3.14
    -3.14
   
print('{0: .2f}n{1: .2f}'.format(pi,-pi))
3.14
-3.14

"{:b}".format(42)
'101010'
"{:#b}".format(42)
'0b101010'
"{:#g}".format(42)
'42.0000'

字符串常用方法

1="font-family: 微软雅黑, 'Microsoft YaHei';">center通过在两边添加填充字符(默认为空格)让字符串居中
"Hi,How old are you".center(30)
'      Hi,How old are you      '
"Hi,How old are you".center(30,"*")
'******Hi,How old are you******'

find在字符串中查找子串,如果找到,就返回子串的第一个字符的索引,否则返回-1
"Hi,How old are you".find("old")
7
tmp = "hello,welcome to you"
tmp.find('hi')
-1
还可以指定搜索的起点与终点
tmp.find("hi",0,10)
-1

join用于合并字符串
s = ['1','2','3','4']
s1="+"
s1.join(s)
'1+2+3+4'
dir = '','usr','bin','env'
'/'.join(dir)
'/usr/bin/env'
print('C:' + '\'.join(dir))
C:usrbinenv

lower转换小写
'HELLOWORLD'.lower()
'helloworld'
</span>

replace替换将指定字符串替换成另一个字符串,并返回替换后结果。

1="font-family: 微软雅黑, 'Microsoft YaHei';">str ="This is a test"
str.replace("is","was")
'Thwas was a test'
</span>

split拆分字符串为序列

1="font-family: 微软雅黑, 'Microsoft YaHei';"> num = '1+2+3+4'
num.split("+")
['1', '2', '3', '4']
'/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
</span>

strip删除行首与行尾的空白行,并返回删除后的结果

1="font-family: 微软雅黑, 'Microsoft YaHei';">'   hello world   '.strip()
'hello world'</span>

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/224137.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号