python入门 之 字符串(二)

注:

来自:《Python 编程 从入门到实践》

环境: windows Python 2.7 

 

Python 之禅

1. 输入代码:

import this

2. 它从本质上阐述了代码的指导原则,其内容如下:

'''
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''

'''
优美胜于丑陋(以编写优美的代码为目标)
明了胜于晦涩(优美的代码应当是明了的,命名规范,风格相似)
简洁胜于复杂(优美的代码应当是简洁的,不要有复杂的内部实现)
复杂胜于凌乱(如果复杂不可避免,那代码间也不能有难懂的关系)
扁平胜于嵌套(优美的代码应当是扁平的,不能有太多的嵌套)
间隔胜于紧凑(优美的代码有适当的间隔,不要奢望一行代码解决问题)
重视可读性(优美的代码是可读的)
尽管实用性会打败纯粹性,特例也不应该凌驾于规则之上
不要包容所有错误,除非你确定需要这样做
面对不明确的定义,拒绝猜测的诱惑
找到一种最好唯一的一种方法去解决问题(如果不确定,就用穷举法)
虽然这并不容易,因为你不是 Python 之父
做也许好过不做,但没有思考过的做还不如不做
如果你无法向人描述你的方案,那肯定不是一个好方案
命名空间是一种绝妙的理念,请多加利用
'''

3. 我们可以在Python27\Lib\this.py中看到该原则的实现:

# this.py
s = """Gur Mra bs Clguba, ol Gvz Crgref

Ornhgvshy vf orggre guna htyl.
Rkcyvpvg vf orggre guna vzcyvpvg.
Fvzcyr vf orggre guna pbzcyrk.
Pbzcyrk vf orggre guna pbzcyvpngrq.
Syng vf orggre guna arfgrq.
Fcnefr vf orggre guna qrafr.
Ernqnovyvgl pbhagf.
Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.
Nygubhtu cenpgvpnyvgl orngf chevgl.
Reebef fubhyq arire cnff fvyragyl.
Hayrff rkcyvpvgyl fvyraprq.
Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff.
Gurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg.
Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.
Abj vf orggre guna arire.
Nygubhtu arire vf bsgra orggre guna *evtug* abj.
Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.
Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.
Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!"""

'''
chr: 用于将0~255范围内的整数转换为字符,比如:chr(65)为'A' chr(97)为'a'
'''
d = {}
for c in (65, 97):
    for i in range(26):
        d[chr(i+c)] = chr((i+13) % 26 + c)

'''
d = {'A': 'N', 'C': 'P', 'B': 'O', 'E': 'R', 'D': 'Q', 'G': 'T', 'F': 'S', 'I': 'V', 'H': 'U', 'K': 'X',
'J': 'W', 'M': 'Z', 'L': 'Y', 'O': 'B', 'N': 'A', 'Q': 'D', 'P': 'C', 'S': 'F', 'R': 'E', 'U': 'H',
'T': 'G', 'W': 'J', 'V': 'I', 'Y': 'L', 'X': 'K', 'Z': 'M', 'a': 'n', 'c': 'p', 'b': 'o', 'e': 'r',
'd': 'q', 'g': 't', 'f': 's', 'i': 'v', 'h': 'u', 'k': 'x', 'j': 'w', 'm': 'z', 'l': 'y', 'o': 'b',
'n': 'a', 'q': 'd', 'p': 'c', 's': 'f', 'r': 'e', 'u': 'h', 't': 'g', 'w': 'j', 'v': 'i', 'y': 'l',
'x': 'k', 'z': 'm'}
''' print "".join([d.get(c, c) for c in s])

对照着d的数据我们可以发现其关系为

大写字母:A -> N,C -> P, B -> O ...

小写字母: a -> n,  c -> p b -> o ...

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm

其对照图为:

 

Gur Mra bs Clguba 参考对照图就会变成 The Zen of Python。

这个属于ROT13(回转13位)的一种替换式密码,属于对称加密。加密和解密都是同一套算法,属于凯撒加密的一种变体,一段文字按照字母顺序只需要将当前字母用13位之后的对应字母替代,超过第13位的字母则重新回到字母开头。而该加密算法的最终实现就是python 设计之禅。

 

基本使用:

一般使用字符串通过单引号或者双引号或者三引号标记,比如:

print('string')
print("string")

# 三引号一般用于段落
_str = """ONe 
Two
Three"""
print(_str)

假设说,我们想在字符串中使用单引号,比如: 

# This is 'Python'

# 单引号进行套用会报错,我们可以使用双引号:
print("This is 'Python' ")

# 使用转义字符
'''
\'    代表单引号
\"    代表双引号  
\t    代表制表符
\n    代表换行符
\\    代表倒斜杠 
'''
print('This is \'Python\'')
print("This is \'Python\'") 

在上面提到我们可以使用转义字符实现一些特殊操作,如果想在程序中将转义字符作为字符串打印出来的话,我们可以这样做:

# 在字符的前面添加 r 标记,说明这是原始字符串
print(r'This is \'Python\'')         # This is \'Python\'

print('Hello\tPython')              # Hello    Python
print(r'Hello\tPython')             # Hello\tPython

原始字符串在正则表达式中很有用,故此说明下。

 

其常用的运算符有:

运算符 描述 示例
+ 字符串连接 'A' + 'b' --> Ab
* 重复输出 'a' * 3 --> aaa
[]

根据索引获取指定字符串

注意:不可超过字符最大长度

_str = 'A B'

_str[-1] --> B

_str[len(_str) -1] --> B

[:] 截取字符串指定部分

_str = 'ABC'

_str[0:2] --> AB

in

若包含指定字符,返回True

注意:区分大小写

print('c' in 'AB') --> False

print('C' in 'ABC') --> True

not in

若不包含指定字符,返回False

注意:区分大小写

 

print('c' not in 'AB') --> True

print('C' not in 'ABC') --> False

常用方法:

1. 数字与字符串的相互转化:

print('Add:' + str(100))    # Add:100
print(int('100') * 2)       # 200
print(float('10') * 2)      # 20.0

2. 字符串的字母大小写

# 将字符串的首字母大写
print('hi,boy'.title())             #Hi,Boy
# 将字符串所有字符大写
print('hi,boy'.upper())             #HI,BOY
# 将字符串所有字符小写
print('Hello World'.lower())        #hello world

3. 删除字符串开头或结尾空格

# 删除字符串开头空格,若未重新赋值,其删除是暂时的
strName = '   String'
print(strName.lstrip())         #String
print(strName)                  #   String

# 删除字符串结尾空格,若未重新赋值,其删除是暂时的
strName = 'String    '
print(strName.rstrip() + 'Space')         #StringSpace
print(strName + 'Space')                  #String    Space

# 删除字符串首尾空格,若未重新赋值,其删除是暂时的
strName = '   String     '
print(strName.strip() + 'space')         #StringSpace
print(strName + 'space')                 #   String     space

4. 获取字符串长度及制定字符相关

# 获取字符串长度
print(len('He llo'))    # 6

# 获取字符串最大(最小)字符
print(max('abdef'))         #f
print(min('abc'))           #a

# 获取字符串中指定字符出现个数 
_str = 'aabca'
'''
参数:
    指定字符
    开始位置,默认为 0
    结束位置,默认为 len(str)
'''
print(_str.count('a'))          # 3
print(_str.count('a',0,2))      # 2

5. 判定字符串是否都是大写或者小写字母,返回结果为布尔值

# 判定字符或者字符串是否为大写字母
print('a'.isupper())        # False
print('AB'.isupper())       # True
print('Hello'.isupper())    # False 

# 判定字符或者字符串是否为小写字母
print('a'.islower())        # True
print('AB'.islower())       # False
print('Hello'.islower())    # False 

拓展:

# 判定字符串是否仅包含字母,且非空
print('hello'.isalpha())        # True
print('a b'.isalpha())          # False
print('a123'.isalpha())         # False

# 判定字符串是否仅包含字母和数字,且非空
print('hello'.isalnum())        # True
print('a b'.isalnum())          # False
print('a123'.isalnum())         # True 

# 判定字符串中是否仅包含数字,且非空
print('hello'.isspace())        # False
print('\n \t'.isspace())        # True
print('a123'.isspace())         # False

# 判定字符串中是否以大写字母开头
print('Hello'.istitle())        # True
print('AB'.istitle())           # False
print('a123'.istitle())         # False 

6. 字符串列表连接和分割

# 将字符串列表连接起来
_tab = ['This ', 'is ', 'Python']
print(''.join(_tab))            # This is Python

# 将字符串分割
msg = 'This is Python'
# 默认情况下,按照空白字符分割
print(msg.split())              # ['This', 'is', 'Python']
# 可以指定字符或者字符串
msg = 'This#is#Python'
print(msg.split('#'))           # ['This', 'is', 'Python']

7. 字符串对齐文本

# 左对齐,默认以空格字符代替,可使用其他字符
print('Hello'.ljust(10))            # Hello
print('Hello'.ljust(10,'='))        # Hello=====

# 右对齐,默认以空格字符代替,可使用其他字符
print('Hello'.rjust(10))            #      Hello
print('Hello'.rjust(10,'='))        # =====Hello

# 居中对齐
print('Hello'.center(10))            #   Hello
print('Hello'.center(10,'='))        # ==Hello===

8. 其他

msg = 'Hello Python'

# 判定是否以指定字符或者字符串开始
print(msg.startswith('h'))      # False
print(msg.startswith('Hello'))  # True

# 判定是否以指定字符串或者字符串结尾
print(msg.endswith('N'))        # False
print(msg.endswith('on'))       # True

 

字符串格式化

1. 使用字符格式化符号,比如:

_str = 'My Name:%s Weight:%d kg Height: %f cm' % ('Python', 2,2)
print(_str)  # My Name:Python Weight:2 kg Height: 2.000000 cm

2. 使用format

# 不设置指定位置,按照默认顺讯来
_str = 'My Name is {} and Weight is {} kg'.format('Python', 2)
print(_str)         # My Name is Python and Weight is 2 kg

# 设置指定位置
_str = 'My Name is {0} and Weight is {1} kg'.format('Python', 2)
print(_str)         # My Name is Python and Weight is 2 kg

_str = 'My Name is {0} and Weight is {1} kg {0}'.format('Python', 2)
print(_str)         # My Name is Python and Weight is 2 kg Python

# 设置参数
_str = 'My Name is {name} and Weight is {weight} kg'.format(name = 'Python', weight = 2)
print(_str)         # My Name is Python and Weight is 2 kg

2.1 使用format对数字格式化,有如下几种:

# 保留小数点后几位
print('{:.3f}'.format(3.14156))         # 3.142
# 带+号保留小数点后几位
print('{:+.2f}'.format(-3.0067))        # -3.01
# 不带小数
print('{:.0f}'.format(-3.0154))         # -3      
print('{:.0f}'.format(3.4654))          # 3
# 以逗号分隔数字
print('{:,}'.format(100000))            # 100,000

# 显示百分比
print('{:.2%}'.format(0.256))           # 25.60%

# 数字补0
print('{:0>2d}'.format(5))              # 05    左边填充,数字宽度为2
print('{:0<3d}'.format(5))              # 500   右边填充,数字宽度为3

# 数字补其它
print('{:x>2d}'.format(5))              # x5
print('{:s>2d}'.format(5))              # s5
print('{:#>2d}'.format(5))              # #5

# 若 : 后没有数字或者字符,则以空格填充,可用来对比
print('{:x>10d}'.format(13))            #xxxxxxxx13
print('{:>10d}'.format(13))             #        13

 

posted @ 2018-11-30 00:16  Code~  阅读(329)  评论(0编辑  收藏  举报