python字符串

字符串不可变

str = 'hello world'
# str[0] = 't' 会报错
str.replace('world','lds')                                #可以使用replace重新赋值
s = bytearray('abcde')                                #或者使用bytearray代替字符串
s[1:3] = '12'

数据分类
可变数据类型 list, dictionary, set, numpy array, user defined objects
不可变数据类型integer, float, long, complex, string, tuple, frozenset

字符串不可改变的原因

其一,列表可以通过以下的方法改变,而字符串不支持这样的变化。

a = [1, 2, 3, 4]
b = a

此时, a 和 b 指向同一块区域,改变 b 的值, a 也会同时改变:

b[0] = 100
a

其二,是字符串与整数浮点数一样被认为是基本类型,而基本类型在Python中是不可变的。

多行字符串

使用"""或者’’'来生成

a = """hello world.
it is a nice day."""
print(a)

输出
hello world.
it is a nice day.
在存储时,用\n来存储换行

a

输出 ‘hello world.\nit is a nice day.’
使用()或\换行

a = ("hello, world. "
    "it's a nice day. "
    "my name is xxx")
b = "hello, world. " \
    "it's a nice day. " \
    "my name is xxx"

输出 “hello, world. it’s a nice day. my name is xxx”

强制转换字符串

str() repr()
二者将object转换成字符串

 >>str('hello\n')
 'hello\n'
>>repr('hello\n')
"'hello\\n'"

整数与不同进制转换

hex(255)                                   #'0xff'
oct(255)                                    #'0377'
bin(255)                                    #'0b11111111'
int('23')                                     #23
int('FF', 16)                              #255
int('377', 8)                              #255
float('3.5')                                #3.5

格式化%

image.png

强调%s与%r区别

string = "hello\tWillWill\n"
print("%s"%string)     #hello	Will
print("%r"%string)      #'hello\tWill\n'

格式化操作符辅助符

image.png

num = 100
f = 3.1415
print("%d %x"%(num,num))             #100 64
print("%d %#x"%(num,num))           #100 0x64
print("%.3f"%f)                                 #3.142
print("%10.3f"%f)                             #     3.142  共10个位置,又对齐
print("%-10.3f"%f)                           #3.142
 print("%010.3f"%f)                         #000003.142

字符串模板(Template)

from string import Template
s = Template("Hi, $name! $name is learning $language")      
print(s.substitute(name="Wilber", language="Python"))              #Hi, Wilber! Wilber is learning Python

d = {"name": "Will", "language": "C#"}
print(s.substitute(d))                                             #Hi, Will! Will is learning C#

#使用$$输出美元$符号 
s = Template("This book ($bname) is 17$$")
print(s.substitute(bname="TCP/IP"))                #This book (TCP/IP) is 17$

字符串内建函数format()

使用{}格式化

# 位置参数
print("{0} is {1} years old".format("Wilber", 28))
print ("{} is {} years old".format("Wilber", 28))
print ("Hi, {0}! {0} is {1} years old".format("Wilber", 28))

# 关键字参数
print ("{name} is {age} years old".format(name = "Wilber", age = 28))

# 下标参数
li = ["Wilber", 28]
print ("{0[0]} is {0[1]} years old".format(li))

# 填充与对齐
# ^、<、>分别是居中、左对齐、右对齐,后面带宽度
# :号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
print ('{:>8}'.format('3.14'))
print ('{:<8}'.format('3.14'))
print ('{:^8}'.format('3.14'))
print ('{:0>8}'.format('3.14'))
print ('{:a>8}'.format('3.14'))

# 浮点数精度
print ('{:.4f}'.format(3.1415926))
print ('{:0>10.4f}'.format(3.1415926))

# 进制
# b、d、o、x分别是二进制、十进制、八进制、十六进制
print('{:b}'.format(11))
print ('{:d}'.format(11))
print ('{:o}'.format(11))
print ('{:x}'.format(11))
print ('{:#x}'.format(11))
print ('{:#X}'.format(11))

# 千位分隔符
print ('{:,}'.format(15700000000)))

str 内建函数

dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', 
'__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', 
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', 
'__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 
'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric',
 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind',
 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 
'upper', 'zfill']

常用的内建函数

S = "s123STRstr"
# 小写 
S.lower() 
# 大写 
S.upper() 
#大小写互换 
S.swapcase() 
# 首字母大写 
S.capitalize() 

# 输出width个字符,S左对齐,不足部分用fillchar填充,默认的为空格。 
S.ljust(width,[fillchar]) 
# 右对齐 
S.rjust(width,[fillchar]) 
# 中间对齐 
S.center(width, [fillchar]) 

# 返回S中出现substr的第一个字母的标号,如果S中没有substr则返回-1。start和end作用就相当于在S[start:end]中搜索 
S.find(substr, [start, [end]]) 
# 返回S中最后出现的substr的第一个字母的标号,如果S中没有substr则返回-1,也就是说从右边算起的第一次出现的substr的首字母标号 
S.rfind(substr, [start, [end]]) 
# 计算substr在S中出现的次数 
S.count(substr, [start, [end]]) 
#把S中的oldstar替换为newstr,count为替换次数
S.replace(oldstr, newstr, [count]) 

# 把S中前后chars中有的字符全部去掉,可以理解为把S前后chars替换为None 
S.strip([chars]) 
S.lstrip([chars]) 
S.rstrip([chars]) 

# 以sep为分隔符,把S分成一个list。maxsplit表示分割的次数。默认的分割符为空白字符 
S.split([sep, [maxsplit]]) 
# 把seq代表的字符串序列,用S连接起来 
S.join(seq)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值