#python学习笔记(七)#字符串

目录

1 A string is a sequence

2 Strings are immutable

3 Looping the string

4 String comparision

5 String method


1 A string is a sequence

▲可以用bracket[ ]取字符串里的字符,第一项为0,最后一项为字符串长度-1

>>> fruit = 'banana'
>>> letter = fruit[1]
>>> print(letter)
a

[ ]还可以用于取出某个字段

>>> s = 'Monty Python'
>>> print(s[0:5])        ####取第0到第5项,但不包括5,即第1-4个字符
Monty
>>> print(s[6:13])       ####取第6到第12项,但不包括13,即第6-12个字符,最后一个数字可以溢出
Python
>>>print(s[13])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range   ####但是取单个字符溢出会报错

>>> fruit = 'banana'
>>> fruit[:3]             ####取到第3项但不包括第3项
'ban'
>>> fruit[3:]             ####从第3项开始取到最后
'ana'

len函数返回字符串的长度,空格也占一个长度 

>>> len('Hello world!')
12

2 Strings are immutable

▲字符串是不可变的,这意味着你不能改变字符串里的某个字符

>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
TypeError: 'str' object does not support item assignment


>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]   ####但是可以生成一个新的字符串
>>> print(new_greeting)
Jello, world!

3 Looping the string

 ▲循环语句遍历字符串

####while语句
index = 0
while index < len(fruit):
    letter = fruit[index]
    print(letter)
    index = index + 1


####for语句,更简洁
for char in fruit:
    print(char)

▲示例:计算字符串长度

word = 'banana'
count = 0
for letter in word:
    if letter == 'a':
        count = count + 1
print(count)

4 String comparision

in是一个Boolean operator布尔运算符,判断字段是否在字符内部

>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False

 ▲字符串大小比较对两个字符每一位逐一比较,依据其在字母表的顺序比较大小

>>> 'banana'=='banana'
True
>>>
>>> 'Banana'>'banana'
False
>>> 'Banana'<'banana'    ####s所有的大写字母排在小写字母前
True

5 String method

Strings are an example of Python objects. An object contains both data (the actual string itself) and methods, which are effectively functions that are built into the object and are available to any instance of the object.

字符串是python的一个对象,除了包含字符串的值外,还要许多可以应用于字符串的函数储存在method方法里

>>> stuff = 'Hello world'
>>> type(stuff)
<class 'str'>
>>> dir(stuff)                 ####dir函数列出字符串stuff的方法
['capitalize', 'casefold', 'center', 'count', 'encode',
'endswith' , 'expandtabs', 'find', 'format', 'format_map',
'index' , 'isalnum', 'isalpha', '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']
>>> help(str.capitalize)                                     ####help函数返回方法的介绍
Help on method_descriptor:
capitalize(...)
S.capitalize() -> str 
Return a capitalized version of S, i.e. make the first character
have upper case and the rest lower case.


>>> word = 'banana'
>>> new_word = word.upper()       ####str字符串+。+方法名()调用方法
>>> print(new_word)
BANANA

 ▲具体的方法介绍见上一篇文章https://blog.csdn.net/weixin_38980061/article/details/120876702?spm=1001.2014.3001.5502

▲字母大小写类:

  str.capitalize()、str.casefold()、str.lower()、str.swapcase()、str.title()、str.upper()

▲字符填充类:

  str.center(width[, fillchar])、str.join(iterable)、str.ljust(width[, fillchar])、str.rjust(width[, fillchar])、str.zfill(width)

▲查找计数类:

  str.count(sub[, start[, end]])、str.endswith(suffix[, start[, end]])、str.find(sub[, start[, end]])、str.index(sub[, start[, end]])、str.replace(old, new[, count])、str.rfind(sub[, start[, end]])、str.rindex(sub[, start[, end]])、str.startswith(prefix[, start[, end]])

▲字段删除类:

  str.expandtabs(tabsize=8)、str.lstrip([chars]、str.removeprefix(prefix, /)、str.removesuffix(suffix, /)、str.rstrip([chars])、str.strip([chars])

▲字符拆分类:

  str.partition(sep)、str.rpartition(sep)、str.rsplit(sep=None, maxsplit=- 1)、str.split(sep=None, maxsplit=- 1)

▲判断类型类:

  str.isalnum()、str.isalpha()、str.isascii()、str.isdecimal()、str.isdigit()、str.isidentifier()、str.islower()、str.isnumeric()、str.isprintable()、str.isspace()、str.istitle()、str.isupper()

▲其他:

  str.format(*args, **kwargs)


▲示例:用str.find()函数解析字符

str.find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

在字符串中查找某字符,start和end表示查找区间,返回找到的位置,没找到返回-1

>>> 'banana'.find('na')
2
>>> 'banana'.find('na',3)
4
>>> 'banana'.find('za')
-1
######从字符串中解析uct.ac.za


>>> data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
>>> atpos = data.find('@')   ###查找@位置
>>> print(atpos)
21
>>> sppos = data.find(' ',atpos)   ###查找@后第一空格的位置
>>> print(sppos)
31
>>> host = data[atpos+1:sppos]     ###根据两个位置提取字段
>>> print(host)
uct.ac.za
>>>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值