python——字符串

简介: raw字符串(原始字符串)所见即所得,例如print('\n')print(r'\n')\nlen('\n')1len(r'\n')2Unicode 字符串ASCII码:每个字符都是以7位二进制数的方式存储在计算机内,ASCI字符只能表示95个可打印字符。

raw字符串(原始字符串)

所见即所得,例如

print('\n')
print(r'\n')
\n
len('\n')
1
len(r'\n')
2

Unicode 字符串

  • ASCII码:每个字符都是以7位二进制数的方式存储在计算机内,ASCI字符只能表示95个可打印字符。
  • Unicode:通过使用一个或多个字节来表示一个字符的方式突破了ASCII码的限制。

示例:

'\nabc'
'\nabc'
u'\nabc'
'\nabc'
u'刘备'
'刘备'
U'卓越'
'卓越'

Python转义字符

在需要在字符中使用特殊字符时,python用反斜杠(\)转义字符。如下表:

转义字符 描述
\(在行尾时) 续行符
\\ 反斜杠符号
\' 单引号
\" 双引号
\a 响铃
\b 退格(Backspace)
\e 转义
\000
\n 换行
\v 纵向制表符
\t 横向制表符
\r 回车
\f 换页
\oyy 八进制数,yy代表的字符,例如:\o12代表换行
\xyy 十六进制数,yy代表的字符,例如:\x0a代表换行

格式化操作

python字符串格式化符号:

符   号 描述
%c 转换成字符(ASCII码值或长度为1的字符串)
%s 优先使用str()函数进行字符串转换
%r 优先使用repr()函数进行字符串转换
%u 转换为无符号十进制
%d 转换为有符号十进制
%o 转换为无符号八进制数
%x/%X 转换为无符号十六进制数
%f 转换为浮点数字,可指定小数点后的精度
%e/%E 用科学计数法格式化浮点数
%g %f和%e的简写
%G %f%E 的简写
%p 用十六进制数格式化变量的地址
%% 输出%

格式化操作符辅助指令:

符号 功能
* 定义宽度或者小数点精度
- 用做左对齐
+ 在正数前面显示加号(+ )
<sp> 在正数前面显示空格
# 在八进制数前面显示零('0'),在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X')
0 显示的数字前面填充'0'而不是默认的空格
% '%%'输出一个单一的'%'
(var) 映射变量(字典参数)
m.n. m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)

形式:
format%values

values的输入形式:

  • 元组形式
  • 字典形式(键作为format出现,字典作为values存在)
print('hello %s, %s enough!'%('world','happy'))
hello world, happy enough!
print('int:%d,str:%s,str:%s'%(1.0,['in list','i am list'],'i am str'))
int:1,str:['in list', 'i am list'],str:i am str
'%x'%100
'64'
'%X'%110
'6E'
'we are at %d%%'%100
'we are at 100%'
'%s is %d years old'%('Li',20)
'Li is 20 years old'
for i in range(1000,10000):
    a=int(i/1000)
    b=int(i/100)%10
    c=(int(i/10))%10
    d=i%10
    if a**4+b**4+c**4+d**4==i:
        print('%d=%d^4+%d^4+%d^4+%d^4'%(i,a,b,c,d))
1634=1^4+6^4+3^4+4^4
8208=8^4+2^4+0^4+8^4
9474=9^4+4^4+7^4+4^4

m.n 宽度与精度

'%.3f'%123.12345
'123.123'
'%.5s'%'hello world'
'hello'
'%+d'%4
'+4'
'%+d'%-4
'-4'
from math import pi
'%-10.2f'%pi
'3.14      '
'%10.4f'%pi
'    3.1416'
'My name is %(name)s,age is %(age)d,gender is %(gender)s'%{'name':'LiMing','age':28,'gender':'male'}
'My name is LiMing,age is 28,gender is male'

字符串模板

字符串对象Template对象存在与string模块中:

  • 使用美元符号$定义代替换的参数
  • 使用substitute()方法(缺少参数时会报错,KeyError异常) & safe_substitute()方法(缺少key时,直接显示参数字符串)进行参数替换

示例:

from string import Template
s=Template('There are ${how_many} nodes in the ${tree}')
print(s.substitute(how_many=32,tree='splay_tree'))
There are 32 nodes in the splay_tree
print(s.substitute(how_many=32))
---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-4-6c5e84463638> in <module>()
----> 1 print(s.substitute(how_many=32))


D:\ProgramData\Anaconda3\lib\string.py in substitute(*args, **kws)
    124             raise ValueError('Unrecognized named group in pattern',
    125                              self.pattern)
--> 126         return self.pattern.sub(convert, self.template)
    127 
    128     def safe_substitute(*args, **kws):


D:\ProgramData\Anaconda3\lib\string.py in convert(mo)
    117             named = mo.group('named') or mo.group('braced')
    118             if named is not None:
--> 119                 return str(mapping[named])
    120             if mo.group('escaped') is not None:
    121                 return self.delimiter


KeyError: 'tree'
from string import Template
s=Template('There are ${how_many} nodes in the ${tree}')
print(s.safe_substitute(how_many=32))
There are 32 nodes in the ${tree}

Python 的字符串常用内建函数

1 S.capitalize() 返回一个首字母大写的字符串(str):

a = "this is string example from runoob...wow!!!"
print ("a.capitalize() : ", a.capitalize())
a.capitalize() :  This is string example from runoob...wow!!!

2 S.lower -> Return a copy of the string S converted to lowercase

'HGKFKF'.lower()
'hgkfkf'

3 S.center(width[, fillchar])

参数:

  • width:字符串的总宽度
  • fillchar填充字符(默认为空格)

返回值:

  • 一个指定的宽度width居中的字符串
  • 如果width小于字符串宽度直接返回字符串,否则使用fillchar去填充
st = "[www.runoob.com]"
print ("st.center(40, '%') : ", st.center(40, '%'))
st.center(40, '%') :  %%%%%%%%%%%%[www.runoob.com]%%%%%%%%%%%%

4 S.count(sub[, start[, end]]) 该方法返回子字符串在字符串中出现的次数

  • sub -- 搜索的子字符串
  • start -- 字符串开始搜索的位置。默认为第一个字符。
  • end -- 字符串中结束搜索的位置。默认为字符串的最后一个位置。
st="www.runoob.com"
sub='o'
print ("st.count('o') : ", st.count(sub))

sub='run'
print ("st.count('run', 0, 10) : ", st.count(sub,0,10))
st.count('o') :  3
st.count('run', 0, 10) :  1

5 bytes.decode(self, /, encoding='utf-8', errors='strict')

  • encoding -- 要使用的编码,如"UTF-8"。
  • errors -- 设置不同错误的处理方案。默认为'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。

返回该方法返回解码后的字符串。

6 S.encode(encoding='utf-8', errors='strict') -> bytes

Python3 中str没有decode方法,但是可以使用bytes对象的decode()方法来解码给定的bytes对象,这个bytes对象可以由str.encode()来编码返回。

s = "中国"
s_utf8 = s.encode("UTF-8")
s_gbk = s.encode("GBK")

print(s)

print("UTF-8 编码:", s_utf8)
print("GBK 编码:", s_gbk)

print("UTF-8 解码:", s_utf8.decode('UTF-8','strict'))
print("GBK 解码:", s_gbk.decode('GBK','strict'))
中国
UTF-8 编码: b'\xe4\xb8\xad\xe5\x9b\xbd'
GBK 编码: b'\xd6\xd0\xb9\xfa'
UTF-8 解码: 中国
GBK 解码: 中国

7 S.find(sub[, start[, end]]) -> int

如果包含子字符串返回开始的索引值,否则返回-1。

str1 = "Runoob example....wow!!!"
str2 = "exam";
 
print (str1.find(str2))
print (str1.find(str2, 5))
print (str1.find(str2, 10))
7
7
-1
info = 'abca'
print(info.find('a'))      # 从下标0开始,查找在字符串里第一个出现的子串,返回结果:0

print(info.find('a', 1))   # 从下标1开始,查找在字符串里第一个出现的子串:返回结果3

print(info.find('3'))      # 查找不到返回-1
0
3
-1

8 S.join(iterable) -> str

Return a string which is the concatenation of the strings in the
iterable.

关于iterable参考python——聊聊iterable,sequence和iterators

s1 = "-"
s2 = ""
seq = ("r", "u", "n", "o", "o", "b") # 字符串序列
print (s1.join( seq ))
print (s2.join( seq ))
r-u-n-o-o-b
runoob

9 S.strip([chars]) -> str

  • Return a copy of the string S with leading and trailing whitespace removed.
  • If chars is given and not None, remove characters in chars instead.
st = "     this is string example....wow!!!     ";
print( st.lstrip() );
st = "88888888this is string example....wow!!!8888888";
print( st.lstrip('8') );
print( st.strip('8') );
this is string example....wow!!!     
this is string example....wow!!!8888888
this is string example....wow!!!

10 S.replace(old, new[, count]) -> str

  • Return a copy of S with all occurrences of substring old replaced by new.
  • If the optional argument count is given, only the first count occurrences are replaced.
st = "www.w3cschool.cc"
print ("菜鸟教程新地址:", st)
print ("菜鸟教程新地址:", st.replace("w3cschool.cc", "runoob.com"))

st = "this is string example....wow!!!"
print (st.replace("is", "was", 3))
菜鸟教程新地址: www.w3cschool.cc
菜鸟教程新地址: www.runoob.com
thwas was string example....wow!!!

11 S.split(sep=None, maxsplit=-1) -> list of strings

  • Return a list of the words in S, using sep as the delimiter string.
  • If maxsplit is given, at most maxsplit splits are done.
  • If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.
st = "this is string example....wow!!!"
print (st.split( ))
print (st.split('i',1))
print (st.split('w'))
['this', 'is', 'string', 'example....wow!!!']
['th', 's is string example....wow!!!']
['this is string example....', 'o', '!!!']
探寻有趣之事!
目录
相关文章
|
17天前
|
Python
1167: 分离字符串(PYTHON)
1167: 分离字符串(PYTHON)
|
1月前
|
大数据 Python
使用Python查找字符串中包含的多个元素
本文介绍了Python中查找字符串子串的方法,从基础的`in`关键字到使用循环和条件判断处理多个子串,再到利用正则表达式`re模块`进行复杂模式匹配。文中通过实例展示了如何提取用户信息字符串中的用户名、邮箱和电话号码,并提出了优化策略,如预编译正则表达式和使用生成器处理大数据。
20 1
|
1月前
|
数据挖掘 开发者 Python
Python:字符串判断子串
Python:字符串判断子串
|
1月前
|
程序员 数据安全/隐私保护 Python
Python:翻转字符串
Python:翻转字符串
|
1月前
|
索引 Python
Python系列(14)—— 字符串运算符
Python系列(14)—— 字符串运算符
|
1月前
|
存储 自然语言处理 数据挖掘
Python:计算字符串中每个单词出现的次数
Python:计算字符串中每个单词出现的次数
|
1天前
|
Python
Python 字符串格式化指南
本文介绍了Python中的三种字符串格式化方法:1) 使用 `%` 操作符,如 `%s` 和 `%d`;2) `str.format()` 方法,通过 `{}` 占位符插入变量;3) Python 3.6 引入的 f-strings,直接在字符串内嵌入变量。此外,还提到了高级用法,如格式控制(如指定小数位数)。这些方法有助于更有效地处理和格式化字符串输出。
3 0
|
8天前
|
Python
python学习-函数模块,数据结构,字符串和列表(下)
python学习-函数模块,数据结构,字符串和列表
49 0
|
9天前
|
数据采集 Python
python学习9-字符串
python学习9-字符串
|
17天前
|
Java 索引 Python
Python标准数据类型-字符串常用方法(下)
Python标准数据类型-字符串常用方法(下)
21 1