Python自学(五)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/vivien1997/article/details/96971674
※字符串
定义:
字符串(string)是一个字符的序列
使用成对的单引号或双引号括起来,或者使用三引号(保留字符串中全部信息)
基本运算:
1、长度(len())
>>> s = "hello world"
>>> len(s)
11
2、拼接(+)
>>> s + "abcd"
'hello worldabcd'
3、重复(*)
>>> s * 3
'hello worldhello worldhello world'
4、成员运算符(in):判断一个字符串是否是另一个字符串的子串,返回值:T或F
>>> "hi" in s
False
>>> "my name is vivien" in s
False
>>> "world" in s
True

5、枚举(for):枚举字符串的每个字符
>>> my_str = "hello world"
>>> for char in my_str:
	print(char)	
h
e
l
l
o
 
w
o
r
l
D
实例:编写vowels_count函数,计算一个字符串中元音字母(aeiou或AEIOU)的数目
def vowels_count(s):
    count = 0
    for c in s:
        if c in "aeiouAEIOU":
            count += 1
    return count

str = input("please input a string :")
print("元音字母个数为:",vowels_count(str))
运行结果:
please input a string :hello
元音字母个数为: 2
◎字符串索引(index):
字符串中每一个字符都有一个索引值(下标)
索引从0(前向)或-1(后向)开始
索引运算符[ ]
>>> s = "hello world"
>>> s
'hello world'
>>> s[2]
'l'
>>> s[5]
' '
>>> s[6]
'w'
>>> s[-2]
'l'
>>> s[13]
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    s[13]
IndexError: string index out of range
◎切片(slicing)
选择字符串的子序列
语法[start:finish]:不提供时,start默认第一个字符开始,finish为最后一个字符结束
start:子序列开始位置的索引值
finish:子序列结束位置的下一个字符的索引值
>>> s
'hello world'
>>> s[1:5]
'ello'
>>> s[:]
'hello world'
>>> s[5:18]
' world'
计数参数:接收三个参数[start:finish:countBy],countBy默认为1
>>> s[0:11:2]
'hlowrd'
获取逆字符串 countBy = -1
>>> s[::-1]
'dlrow olleh'
◎字符串是不可变的(immutable)
一旦生成,内容不可改变
>>> s[1] = 'b'
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    s[1] = 'b'
TypeError: 'str' object does not support item assignment
>>> s
'hello world'
改变的方法是:通过切片等操作
>>> s = s[:1]+'a'+s[2:]
>>> s
'hallo world'
◎字符串方法
(1)对象提供的函数:my_str.replace(old,new)生成一个新的字符串,其中使用new替换old子串。
>>> s = s.replace('l','w')
>>> s
'hawwo worwd'
(2)find:查找
>>> s
'hawwo worwd'
>>> s.find('o')
4              #第一次出现的位置
(3)split:拆分
>>> s.split()
['hawwo', 'worwd']
(4)更多关于字符串的函数可以使用dir(s)进行查询
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

◎字符串编写实例:人名游戏
(一)读取人名列表文件name.txt,将每个人名转换为首字母大写,其他字母小写的格式
步骤:
1.文件操作
2.打开文件:f = open(filename,mode)  (mode有r(读、默认)w(写)等)
3.按行读取文件内容:for line in f:pass
4.关闭文件:f.close()
5.写文件f.write(str)
程序:
f = open('name.txt','r')

for line in f:
    line = line.strip()      #strip有去掉字符串开始和结尾的空格、回车等的功能
    print(line.title())      #title即有将开头字母变大写的功能

f.close()
(二)编写一个名为is_panlindrom的函数,判断一个人名是否为回文,”BOB”为回文
程序:
f = open("name.txt","r")
def is_panlindrom(name):
    low = 0
    high = len(name) - 1

    while low < high:
        if name[low] != name[high]:
            return False
        elif name[low] == name[high]:
            low += 1
            high -= 1
        return True


for line in f:
    line = line.strip()
    if is_panlindrom(line):
        print(line)

f.close()
#递归方式
f = open("name.txt","r")
def is_panlindrom_rec(name):
    if len(name) <= 1:
        return True
    else:
        if name[0] != name[-1]:
            return False
        else:
            return is_panlindrom_rec(name[1:-1])

for line in f:
    line = line.strip()
    if is_panlindrom_rec(line):
        print(line)

f.close()
(三)编写函数is_asscending,判断一个人名的字母是否为升序排列(允许重复字母)
程序为:
def is_asscending(name):
    p = name[0]

    for c in name:
        if p > c:
            return False
        p = c
    return True

◎字符串比较
ASCII码表中每一个字符对应一个数字,直接比较对应数字的大小
字符串比较则使用字典序(Dictionary order)
1.先比较两个字符串的第一个字符
2.如果相同则比较下一个字符
3.如果不同则字符串的大小关系由这两个字符的关系决定
4.如果其中一个字符为空(较短),则其更小
>>> 'a' > 'b'
False
>>> 'aaa' < 'aab'
True
◎字符串格式化(Formatting):输出更规范的结果
>>> print("Hello  {}  good  {}.".format(5,'Day'))
Hello  5  good  Day.
格式:(field name:align width.precision type)域名:对齐方式(>右对齐<左对齐) 占用宽度.精度 类型
>>> print("PI is {:9.4f}".format(math.pi))
PI is    3.1416
>>> print("PI is {:e}".format(math.pi))     #e指的是使用科学计数法
PI is 3.141593e+00
◎正则表达式(Regular Expressions)
#判断一个人名是否满足下列模式时
.表示任意字符   \d+表示一系列数字    [a-z]表示一个小写字母
#判断一个人名是否包含C.A模式
程序:
import re

f = open("name.txt")

pattern = '(C.A)'

for line in f:
    name = line.strip()
    result = re.search(pattern,name)
    if result:
        print("Find in {}".format(name))


f.close()
#增加符号
>>> s = 'hello world'
>>> s.ljust(15,'.')
'hello world....'
>>> s.rjust(15)
'    hello world'

猜你喜欢

转载自blog.csdn.net/vivien1997/article/details/96971674