前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python入门:字符串

python入门:字符串

作者头像
py3study
发布2020-01-13 11:32:54
6850
发布2020-01-13 11:32:54
举报
文章被收录于专栏:python3python3python3

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

a = 'http://www.python.org'
a[-3:]='com'
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    a[-3:]='com'
TypeError: 'str' object does not support item assignment

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

format='http:// %s.%s.org'
values= ('www','python')
format % values
'http:// www.python.org'

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

常用的另一种方式

"{},{},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'
# 调用math中的pi模块
from math import pi
"{name} is approximately {value:.3f}.".format(value=pi,name="π")						    
'π is approximately 3.142.'

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

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

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."

设置字符串格式

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

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

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

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

替换字段名

"{} {} {} {}".format(1,2,3,4)						    
'1 2 3 4'
#通过索引来指定那个字段中对应的未命名参数。
"{0} {3} {1} {2}".format(1,2,3,4)						    
'1 4 2 3'

基本转换

print("{pi!s} {pi!r} {pi!a}".format(pi="π"))  
π 'π' '\u03c0'

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

还可以指定转换值的类型

 "The number is {}".format(42)	  
'The number is 42'
"The number is {:f}".format(42)	  
'The number is 42.000000'

或二进制格式

"The number is {:b}".format(42)	  
'The number is 101010'

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

整型:

  •  b 二进制
  • c 字符型,把数字转成表示unicode的字符
  • d 十进制
  • o 八进制
  • x 十六进制,显示小写字母
  • X 十六进制,显示大写字母
  • n 与d行为相同,使用本地的数字表示方式
  • ''(空,没有空格) 与d相同

浮点数

  • e 科学计数法表示,小写e
  • E 科学计数法表示,大写E
  • f 显示为定点数,默认小数点后六位
  • F 同f
  • g 自动选择是否用科学记数法表示
  • G 同g
  • n 同g,使用本地表示方式
  • % 使用百分比表示
  • ''(空) 同g

宽度、精度、和千位符

 "{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'

符号、对齐及填充

 '{: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'

字符串常用方法

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:\usr\bin\env

lower转换小写
'HELLOWORLD'.lower()
'helloworld'

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

str ="This is a test"
str.replace("is","was")
'Thwas was a test'

split拆分字符串为序列

 num = '1+2+3+4'
num.split("+")
['1', '2', '3', '4']
'/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']

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

'   hello world   '.strip()
'hello world'
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-07-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档