Python学习日记---字符串

一、字符序列

  Python字符型变量与其他语言有所不同,因为特殊的命名空间,使得字符串是不可直接更改的

 如何指定显示字符串中特定位置的值?如下

>>> helloString = "Hello World"
>>> helloString[0]
'H'
>>> helloString[5]
' '
>>> helloString[-1]
'd'
>>> helloString[-5]
'W'

由示例可知,方括号[]内的值表示特定位置自左向右 0,1,2....自右向左 -1,-2,-3....


二、索引和分片

 Python采用的事半开区间,包含范围内的起始值,不包含结束值

1.普通的分片和索引

>>> helloString = "Hello World"
>>helloString[:]    #默认值起始位置为0,结束位置为最后元素的后一位置
'Hello World'
>>> helloString[2:5]
'llo'
>>> helloString[2:-2]
'llo Wor'
>>>helloString[-1]   #只有一个参数则用作起始位置,结束位置为默认值
'd'


2.扩展分片

 分片还可以加入第三个参数,指定分片的步长,就是从当前字符和下一字符相隔字符数,默认为1

,当步长为负数时,则表示从串尾部往前提取。示例如下:

>>> digits = "0123456789"
>>> digits[::-1]  #从尾部向前提取,在回文中使用较多
'9876543210'
>>> digits[1::2]   #得到奇数分片
'13579'
>>> digits[0::2]  #得到偶数分片
'02468'
>>> digits[-2::-2]
'86420'
>>> digits[-1::-2]
'97531'

3.复制分片

>>> nameOne = "openex"
>>> nameTwo = nameOne[::-1]
>>> id(nameOne),id(nameTwo)
(5647840, 5648064)
>>> nameOne,nameTwo
('openex', 'xenepo')

    

三、字符串操作             

 1.“+” 运算符可用作两字符串连接  “*” 运算符可用作字符串的复制

>>> A = "Hello"
>>> B = "World"
>>> A+B
'HelloWorld'
>>> A*2+(" "+B)*3
'HelloHello World World World'

   

 2.in运算符

 可用于检测一字符串中是否包含一个字符串

>>>'ab' in 'xxxxxabcc'
True

 3.字符串函数和方法

 函数的使用与C差别不大,方法类似于C++的方法概念如helloString.upper().find("A",1,8)


四、字符串的格式化输出

>>>import math
>>> print ("%-10s,%10s\n%-5d,%5d\n%-8.2f,%.4f"%("ABC","ABC",123,123,math.pi,math.pi))
ABC       ,       ABC
123  ,  123
3.14    ,3.1416

 #类似C语言的printf格式化输出, %[符号][宽度][.精度]code


五、一个回文测试示例:

 不区分大小写

 无视特殊符号,只比较数字和字母

 

import string
TestString = input("Please input the string for test: ")
TestString = TestString.lower() #将字符串中字母变为小写
junk = string.punctuation+string.whitespace #利用预定义字符串,生成特殊符号集合
for char in junk:
    if(char in TestString):
        TestString = TestString.replace(char, "") #字符串替换方法,将char换成""
if(TestString == TestString[::-1]):
    print("%s\n%s"%(TestString,TestString[::-1]))
else:
    print("IT's not a palindrome\nONE1:%s\nONE2:%s"%(TestString,TestString[::-1]))


你可能感兴趣的:(python,日记)