python小白之旅——基础篇2——字符串

1.基础操作

     对于所有语言,字符串都是非常重要的。

操作 解释
s='',s="" 空字符串
s="spam's",s='spam"s' 双引号和单引号交替使用
s="""...""" 三重引用字符串块,不用增加换行符,可以作为块注释用
s=r'\temp\spam\' Raw字符串,不会识别转义字符,写文件夹比较方便
S=b'spam' python3.0中的字节符串(b:binary)
s=u'spam' 源于python2.6中使用的unicode字符串,python3中,指定文档为utf-8编码,可以不需要u
s1+s2 字符串合并
s*3 字符串重复
s[i] 索引,取第i个元素(从0起)
s[i:j]

分页,取第i到j个

s[:3] 到下标3结束

s[5:] 从下标5开始

len(s) 求长度
“a %s  parrot” % kind 字符串格式化表达式
“a {0} parrot”.format(kind) 字符串格式化方法
s.find('pa') 字符串方法调用:搜索
s.rstrip() 移除右边的空格,s.lstrip(),s.strip()
s.replace('pa','xx') 替换
s.split(',') 用占位符分隔,分隔成数组
s.isdigit()

内容测试,是否为数字,

s.isalpha() 是否为字母

s.isalnum()

s.isdecimal()

s.isidentifier() 是否是标识符,如if else

s.isspace()

s.isupper()

s.istitle() 是否首字母大写

s.lower() 转换为小写字母,s.upper()
s.endswith(‘spam’) 是否以指定字符串结束,s.startswith
'spam'.join(strlist) 插入分隔符
s.encode('utf-8') 字符串编码
for x in s:print(x) 迭代
'spam' in s 字符串包含于
[c*2 for c in s] 迭代
map(ord,s)

会根据提供的函数对指定序列做映射

参考:http://www.runoob.com/python/python-func-map.html

   

2.转义符

   表达特殊字符(已经当做语法使用的字符或者一些不可见字符)需要使用转义符

转义 意义
\newline

忽视(连续)

参考:https://ask.csdn.net/questions/671581?ref=myrecommend

\\ 反斜杠(保留\)
\' 单引号(保留')
\" 双引号(保留")
\a 响铃
\b 倒退
\f 换页
\n 新行(换行)
\r 返回
\t 水平制表符
\v 垂直制表符
\N{id} Unicode数据库ID
\uhhhh Unicode 16位的十六进制
\uhhhhhhhh Unicode 32位的十六进制值
\x1A 十六进制值
\o23 八进制值
\0 Null(不是c的字符串结尾)
\other 不转义(保留)
   

3.字符串格式化代码

使用占位符,再替代占位符

代码 例子 意义
%s
print('hello %s' % 'world')

hello world

字符串(或任何对象)
%r
print('hello %r' % 'world')

hello 'world'

使用repr(表达式),而不时str
%c   字符
%d   十进制
%i   整数
%u   无符号 整数
%o   八进制整数
%x   十六进制整数
%X   x,但打印大写
%e
print('hello %e' % 123)

hello 1.230000e+02

浮点指数
%E
print('hello %E' % 123)
e,但打印大写
%f   浮点十进制
%F   浮点十进制
%g   浮点e或f
%%
print('hello %s%%' % 'world')

hello world%

常量%
     

猜你喜欢

转载自blog.csdn.net/u014112608/article/details/82558053