Python 字符串

Python 字符串

字符串是Python中最流行的类型。我们可以创建只包含在引号字符。 Python把单引号与双引号相同。
创建的字符串是简单的,只要分配给一个变量的值。
例如:
var1 = 'Hello World!'
var2 = "Python Programming"

访问字符串值:

Python不支持的字符类型,这些都是作为一个长度的字符串处理,因此也可以视为一个子串。 要访问的子串,使用方括号切片指数或指数,以获得您的子串:
例如:
#!/usr/bin/python

var1 = 'Hello World!'
var2 = "Python Programming"

print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
这将输出以下结果:
var1[0]:  H
var2[1:5]:  ytho

更新字符串:

可以“update”现有的字符串(重新)分配到另一个字符串变量。其以前的值或一个完全不同的字串完全可以与新的价值。
例如:
#!/usr/bin/python

var1 = 'Hello World!'

print "Updated String :- ", var1[:6] + 'Python'
这将输出以下结果:
Updated String :-  Hello Python

转义字符:

下表是一个逃跑或反斜线符号可以代表的非打印字符的清单。
注:在doublequoted字符串,转义字符被解释;在singlequoted字符串,转义字符被保留。

反斜线 符号 十六进制 字符 描述
\a 0x07 Bell or alert
\b 0x08 Backspace
\cx   Control-x
\C-x   Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x   Meta-Control-x
\n 0x0a Newline
\nnn   Octal notation, where n is in the range 0.7
\r 0x0d Carriage return
\s 0x20 Space
\t 0x09 Tab
\v 0x0b Vertical tab
\x   Character x
\xnn   Hexadecimal notation, where n is in the range 0.9, a.f, or A.F


特别算字符串:

假设A持有'hello'和变量b拥有'Python'的字符串变量:

操作符 描述 例子
+ 串联 - 添加操作两边的值 a + b 将得到 HelloPython
* 重复 - 创建新的字符串,相同的字符串连接的多个副本 a*2 将得到 -HelloHello
[] 切片 - 从给定的索引字符 a[1] will give e
[ : ] 范围切片 - 从给定范围内的字符 a[1:4] will give ell
in 成员关系 - 返回true,如果存在一个字符在给定的字符串 H in a will give 1
not in 成员关系 - 返回true如果不存在一个字符在给定的字符串 M not in a will give 1
r/R 原始字符串 - 禁止转义字符的实际意义。原始字符串的语法是完全正常与异常的原始字符串操作,字母“r”,前面的引号字符串相同。 “R”可以是小写字母(R)或大写字母(R)的,必须放在紧接第一个引号。 print r'\n' prints \n and print R'\n'prints \n
% 格式化 - 执行字符串格式 See at next section


字符串格式化操作符:

Python的最酷的功能之一是字符串格式符%。这个操作符是唯一的字符串,从C的printf()系列函数的包。
例如: 
#!/usr/bin/python

print "My name is %s and weight is %d kg!" % ('Zara', 21)
这将输出以下结果:
My name is Zara and weight is 21 kg!
这是一套完整的符号可以用%的列表:

格式符号 转换含义
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase 'e')
%E exponential notation (with UPPERcase 'E')
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E

其他支持的符号和功能下表中列出:

符号 功能
* argument specifies width or precision
- left justification
+ display the sign
  leave a blank space before a positive number
# add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used.
0 pad from left with zeros (instead of spaces)
% '%%' leaves you with a single literal '%'
(var) mapping variable (dictionary arguments)
m.n. m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)


三重引号:

Python的三重引号允许跨越多条线路,包括逐字换行符,制表符,和任何其他特殊字符的字符串来救援。
三重引号的语法包括三个连续的单引号或双引号。
#!/usr/bin/python

para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print para_str;
这将产生以下结果。注意每一个特殊字符转换为印刷的形式,权利之间的字符串结束的最后一个换行符“了下来。”关闭三重引号。还注意到,换行符出现在一行的末尾明确回车或转义代码(\ n)的:
this is a long string that is made up of
several lines and non-printable characters such as
TAB (    ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
 ], or just a NEWLINE within
the variable assignment will also show up.


原始字符串:

不要把原始字符串作为一个特殊字符的反斜杠。每个人的性格,你把原始字符串保持你写的方式:
#!/usr/bin/python

print 'C:\\nowhere'
这将打印结果如下:
C:\nowhere
现在,让我们使用原始字符串。我们将在r'expression表达如下:
#!/usr/bin/python

print r'C:\\nowhere'
 将打印结果如下:
C:\\nowhere


Unicode字符串:

在Python中的正常字符串在内部存储为8位ASCII,Unicode字符串存储为16位Unicode。这使得更加多样化的字符集,包括在世界上大多数语言的特殊字符。我会限制我的Unicode字符串的处理下列事项:
#!/usr/bin/python

print u'Hello, world!'
将打印结果如下:
Hello, world!
正如你可以看到,Unicode字符串使用前缀U,就像原始字符串使用前缀ŕ的。 

内置字符串的方法:

Python包括以下字符串的方法:

编号 方法和描述
1 capitalize()
利用字符串的第一个字母
2 center(width, fillchar)
与原有中心的字符串返回一个空间填充字符串宽度列
3 count(str, beg= 0,end=len(string))
计数多少次str的字符串,或在子串出现乞求开始索引和结束索引年底
3 decode(encoding='UTF-8',errors='strict')
使用注册进行编码的编解码器解码的字符串。编码默认的默认字符串的编码。
4 encode(encoding='UTF-8',errors='strict')
返回字符串编码的字符串版本的错误,默认是提高一个ValueError除非错误被“忽略”或“取代”。
5 endswith(suffix, beg=0, end=len(string))
判断后缀结尾的字符串或字符串的子串(乞求的起始索引和结束索引的末尾给出);如果是,则返回true,否则返回false
6 expandtabs(tabsize=8)
如果tabsize没有提供扩展字符串中的多个空格的标签,默认为8%tab空格
7 find(str, beg=0 end=len(string))
判断str字符串,或在子串出现乞求开始索引和结束索引结束;回报指数,如果发现,否则返回-1
8 index(str, beg=0, end=len(string))
找到(),但同样会引发一个异常,如果str没有发现
9 isa1num()
如果字符串中有至少1个字符,所有字符都是字母,否则返回false,则返回true.
10 isalpha()
如果字符串中有至少1个字符,所有字符都是字母,否则返回false,则返回true
11 isdigit()
如果字符串只包含数字,否则返回false,则返回true
12 islower()
返回true如果string至少有1套管字符和所有大小写字符和小写,否则为false
13 isnumeric()
返回true如果一个unicode字符串包含只有数字字符,否则返回false
14 isspace()
如果字符串包含空白字符,否则返回false,则返回true
15 istitle()
如果字符串是正确的“titlecased”,否则返回false返回true
16 isupper()
返回true如果字符串中有至少一个大小写字符和大小写字符是大写字母,否则返回false
17 join(seq)
合并(串连)成一个字符串序列SEQ中的元素的字符串表示形式,分隔字符串
18 len(string)
返回字符串的长度。
19 ljust(width[, fillchar])
返回与原字符串的空间填充字符串左对齐,宽度列
20 lower()
转换字符串中所有大写字母为小写
21 lstrip()
在字符串中删除所有的领先空白
22 maketrans()
translate函数返回一个转换表。
23 max(str)
返回从字符串str的最大字母字符
24 min(str)
返回从字符串str分钟的字母字符
25 replace(old, new [, max])
在与新的字符串替换旧的所有事件,或在最最大出现,如果给予最大
26 rfind(str, beg=0,end=len(string))
和find()函数一样,但在串向后搜索
27 rindex( str, beg=0, end=len(string))
和index()函数一样,但在串向后搜索
28 rjust(width,[, fillchar])
返回原字符串右对齐的宽度列空间填充字符串。
29 rstrip()
移除所有的字符串结尾的空白
30 split(str="", num=string.count(str))
分割字符串根据分隔符(STR空间,如果不提供),并返回子串列表;分裂在最NUM子串。
31 splitlines( num=string.count('\n'))
在所有(或num)换行符分割字符串并返回的每一行的换行符删除列表
32 startswith(str, beg=0,end=len(string))
决定如果启动子串str中的字符串或字符串的子串(乞求的起始索引和结束索引的末尾给出);若然,则返回true,否则返回false
33 strip([chars])
同时执行lstrip()和rstrip()对字符串
34 swapcase()
反转的字符串中的所有字母的情况下
35 title()
返回的“titlecased”字符串版本,也就是说,所有的词用大写字母开头,其余均为小写
36 translate(table, deletechars="")
转换字符串根据转换表STR(256字),在德尔字符串中删除那些
37 upper()
转换字符串中的小写字母为大写
38 zfill (width)
返回原始字符串与零leftpadded宽字符;拟用于数字中,zfill()保留给任何迹象(少一个零)
39 isdecimal()
返回true如果一个unicode字符串包含只有十进制字符,否则返回false
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值