python字符串
来源:互联网 发布:windows xp外观 编辑:程序博客网 时间:2024/05/12 22:15
字符串类型在Python中是最流行的。可以通过在引号包围的字符简单地创建它们。Python使用单引号和双引号来表示字符串是一样的。
创建字符串很简单,只要将值分配给一个变量。例如:
var1 = 'Hello World!'var2 = "Python Programming"
访问字符串值:
Python不支持字符类型;这些都被视为一个长度的字符串,因此也被认为是一个子串。
要访问子字符串,用方括号随着指数或索引来获得子切片。下面是一个简单的例子:
#!/usr/bin/pythonvar1 = 'Hello World!'var2 = "Python Programming"print "var1[0]: ", var1[0]print "var2[1:5]: ", var2[1:5]
当执行上面的代码中,产生以下结果:
var1[0]: Hvar2[1:5]: ytho
更新字符串:
可以在“更新”现有的由(重新)分配一个变量赋值给另一个字符串的字符串。新的值可以与它以前的值或一个串完全不同。下面是一个简单的例子:
#!/usr/bin/pythonvar1 = 'Hello World!'print "Updated String :- ", var1[:6] + 'Python'
当执行上面的代码中,产生以下结果:
Updated String :- Hello Python
转义字符:
下表是未转义非打印字符的列表,可以用反斜线符号来表示。
转义字符被解释;在一个单引号和双引号字符串。
Control-xC-x
Control-xe0x1b转义f0x0c换页M-C-x
Meta-Control-x
0x0a新一行nn
八进制表示法,其中n的范围为0.7
0x0d回车s0x20空格
0x09Tab键v0x0b垂直制表x
字符xxnn
十六进制表示法,其中n的范围是从0.9,a.f,或AF
字符串特殊操作符:
假设字符串变量中保存'Hello'和变量b持有'Python':
字符串格式化操作:
Python最酷的功能是字符串格式运算符%。这种操作是唯一的字符串,弥补了C语言的printf()系列函数功能。下面是一个简单的例子:
#!/usr/bin/pythonprint "My name is %s and weight is %d kg!" % ('Zara', 21)
当执行上面的代码中,产生以下结果:
My name is Zara and weight is 21 kg!
下面是完整的,它可以与%符号使用列表:
其他支持的符号和功能如下表:
三重引号:
Python三重引号允许字符串跨越多行,包括逐字换行符,制表符和其他特殊字符。
三重引号语法由三个连续的单引号或双引号。
#!/usr/bin/pythonpara_str = """this is a long string that is made up ofseveral lines and non-printable characters such asTAB ( ) and they will show up that way when displayed.NEWLINEs within the string, whether explicitly given likethis within the brackets [ ], or just a NEWLINE withinthe variable assignment will also show up."""print para_str;
当执行上面的代码中,产生以下结果。请注意如何每一个特殊字符被转换到打印形式,一直到最后的换行符之间的字符串“up”结束闭三重引号。还要注意的是发生或者使用显式回车在一行或它的转义代码( n)的尾部的换行:
this is a long string that is made up ofseveral lines and non-printable characters such asTAB ( ) and they will show up that way when displayed.NEWLINEs within the string, whether explicitly given likethis within the brackets [ ], or just a NEWLINE withinthe variable assignment will also show up.
原始字符串不把反斜杠作为一个特殊字符。把一个原始字符串的每个字符保持写的方式:
#!/usr/bin/pythonprint 'C:owhere'
当执行上面的代码中,产生以下结果:
C:owhere
现在利用原始的字符串。我们表达如下:
#!/usr/bin/pythonprint r'C:owhere'
当执行上面的代码中,产生以下结果:
C:owhere
Unicode字符串:
在Python普通字符串在内部存储为8位ASCII,而Unicode字符串被作为16位Unicode存储。这使得一组字符更加多样化,包括大多数语言在世界上的特殊字符。限制处理Unicode字符串,注意以下几点:
!/usr/bin/pythonprint u'Hello, world!'
当执行上面的代码,产生以下结果:
Hello, world!
正如你所看到的,Unicode字符串使用前缀 u,就像原始字符串使用前缀 r
- Python字符串
- Python 字符串
- python字符串
- python 字符串
- 【python】-字符串
- python 字符串
- python字符串
- python 字符串
- python,字符串
- python 字符串
- Python字符串
- Python字符串
- python字符串
- Python 字符串
- python 字符串
- Python 字符串
- Python字符串
- python 字符串
- 一个listener.ora配置细节的问题
- c++第五次实验
- 成为优秀程序员的有效方法
- 《C专家编程》笔记——怎样在函数库中查找一个符号
- 从github远程库中克隆到本地库中方法
- python字符串
- 标签跳转语句
- VPN错误"734:PPP链接控制协议终止"解决办法
- Android Google Sample
- linux 查看删除进程 ps命令详解
- 字符编码历史
- Redis内存使用优化与存储
- 描述物理内存
- Fresco源码之DraweeController