python基础-04-字符串操作

【README】

本文总结自《python编程快速上手-让繁琐工作自动化》第6章,非常棒的一本书,墙裂推荐;

  • 1)可以把字符串看做列表,即字符串可以使用索引或切片操作字符串;


【6】字符串操作

【6.1】处理字符串

【6.1.1】字符串字面量

1)如何在字符串中包含单引号(python中的字符串以单引号开始和结束);

  • 使用双引号: “this is tom’s cat”
  • 转译字符:'this is tom\‘s cat’
  • 用三重引号的多行字符串 :‘’’ this is tom’s cat ‘’’
print("\n\n=== 字符串字面量")
# 字符串中有单引号
text01 = "this is tom's cat"
text02 = 'this is tom\'s cat'
text03 = '''this is tom's cat '''
print(text01)
print(text02)
print(text03)

# this is tom's cat
# this is tom's cat
# this is tom's cat

【补充】#号用于单行注释,多行注释使用多行字符串三重引号 ‘’’

print('使用三重引号注释多行-start')
'''
    代码行1
    代码行2
    代码行3
    ....
'''
print('使用三重引号注释多行-end')
# 使用三重引号注释多行-start
# 使用三重引号注释多行-end

2)原始字符串: 在字符串开始的单引号前加上r,表示这个字符串是原始(raw=原生)字符串; 原始字符串完全忽略字符串中的所有转译字符,可以输出字符串中的转译字符;

# 原始字符串
text04 = r'this is tom\'s cat'
print("text04 = " + text04)
# text04 = this is tom\'s cat

【6.1.2】字符串索引和切片(字符串看做列表)

1)字符串:把字符串看做一个列表,字符串中的每个字符都是一个元素,即字符串也可以使用索引和切片;

print('\n\n=== 字符串索引与切片')
text01 = 'hello world !'
print(text01[0]) # h
print(text01[-1]) # !
print(text01[0:5]) # hello 打印0到4的字符,不包括5
subText01 = text01[0:5]
print(subText01) # hello
print(text01) # hello world !


【6.1.3】字符串的in与not in 操作

print('hello' in text01) # True
print('hello' not in text01) # False


【6.2】将字符串放入到其他字符串

1)将字符串放入到其他字符串

  • 方法1: 用 + 操作符拼接字符串
  • 方法2: 利用字符串插值
  • 方法3: 使用 f 字符串; (显然, f=format,格式化的意思,与java类似)
# 6.2 将字符串放入到其他字符串
# 方法1 用 + 操作符拼接字符串
# 方法2: 利用字符串插值
name = 'AI'
age = 33
print('my name is %s, i am %s yeas old' % (name, age))
# 方法3: 使用f字符串
print(f'my name is {name}, i am {age} yeas old')

# my name is AI, i am 33 yeas old
# my name is AI, i am 33 yeas old


【6.3】有用的字符串方法

【6.3.1】字符串方法 upper() lower() isupper() islower()

print("\n\n=== 字符串方法 upper() lower() isupper() islower()")
text01 = 'Hello world'
print(text01.upper()) # 全部转为大写
print(text01.lower()) # 全部转为小写
print(text01.isupper()) # 是否全部为大写 False
print(text01.islower()) # 是否全部为小写 False
print(text01.upper().isupper()) # 是否全部为大写 True
print(text01.lower().islower()) # 是否全部为小写 True

# HELLO WORLD
# hello world
# False
# False
# True
# True


【6.3.2】isX()字符串的布尔方法 isalpha() isalnum() isdecimal() isspace() istitle()

1)isX()方法列表:

  • isalpha(): 如果字符串只包含字母,并且非空,则返回True;
  • isalnum():如果字符串只包含字母和数字,并且非空,则返回True;
  • isdecimal() : 如果字符串只包含数字字符,并且非空,则返回True;
  • isspace() : 如果字符串只包含空格,制表符,换行符,并且非空,则返回True;
  • istitle() : 如果字符串仅包含以大写字母开头, 后面都是小写字母的单词,数字或空格,则返回True
print('\n\n===isX()字符串方法 isalpha()  isalnum()  isdecimal()  isspace()  istitle()')
print('hello'.isalpha()) # True
print('hello123'.isalnum()) # True
print('123'.isdecimal()) # True
print(' '.isspace()) # True
print('Hello123'.istitle()) # True


【6.3.3】字符串方法 startswith() 与 endswith()

1)startswith(target) :字符串是否以target开头; endswith(target):字符串是否以target作为结尾;

print('\n\n===字符串方法 startswith() 与 endswith()')
print('Hello123'.startswith('Hello')) # True
print('Hello123'.startswith('hello')) # False
print('Hello123'.endswith('123')) # True
print('Hello123'.endswith('12')) # False


【6.3.4】6.3.4 字符串方法join-拼接和split-分割字符串

# join() 对字符串列表做连接
print('\n\n=== join() 对字符串列表做连接')
list01 = ['aa', 'bb', 'cc']
joinResult = ','.join(list01)
print(joinResult) # aa,bb,cc

print('\n\n=== split() 把字符串分割为字符串列表')
joinResult = 'hello#world'
list02 = joinResult.split('#')
print(list02) # ['hello', 'world']
print(joinResult.split('ll'))  # ['he', 'o#world']


【6.3.5】partition()分隔字符串(输出包含3个子字符串的元组)

1)partition()字符串函数:将字符串分成分隔符字符串前后的文本,返回包含3个子字符串的元组,包括分隔符之前的文本,分隔符本身,分隔符之后的文本; (注意是元组,不可变;与列表的区别之一是,列表可变

print('\n\n===partition()分隔字符串')
text01 = 'Hello world'
partitionResult = text01.partition('worl')
print(partitionResult) # ('Hello ', 'worl', 'd')

partitionResult02 = text01.partition('tom')
print(partitionResult02) # ('Hello world', '', '')

# 利用多重赋值技巧接收partition()的结果
before, seperator, after = text01.partition('worl')
print(before)  # Hello
print(seperator) # worl
print(after) # d

【补充】python的多重赋值,类似与react的解构赋值,把复杂数据结构解开赋值给多个变量



【6.3.6】用rjust,ljust(),center方法对齐文本

1)rjust(),ljust() 通过插入空格或其他填充符号如*号来对齐文本;

print('\n\n=== 使用 rjust(), ljust(), center() 对其文本')
print('Hello'.rjust(10))
print('Hello'.rjust(10, '*'))
print('Hello'.ljust(10))
print('Hello'.ljust(10, '*'))
print('Hello'.center(10))
print('Hello'.center(10, '*'))

#      Hello
# *****Hello
# Hello
# Hello*****
#   Hello
# **Hello***


【6.3.7】使用strip(), rstrip()和lstrip()删除空白字符

1)删除空白字符串方法:

  • strip(): 删除字符串前后的空白字符;
  • rstrip(): 删除字符串右边的空白字符;
  • lstrip(): 删除字符串左边的空白字符;
print('\n\n===使用strip(), rstrip()和lstrip()删除空白字符')
str07 = '  hello '
print('[' + str07.strip() + ']') # [hello]
print('[' + str07.rstrip() + ']') # [  hello]
print('[' + str07.lstrip() + ']') # [hello ]


【6.4】使用ord()和chr() 转换单字符字符串

1)转换单字符字符串:

  • 使用ord()获取单字符字符串的ascii码
  • 使用chr()函数获取ascii码对应的单字符字符串
print('\n\n===使用ord()获取单字符字符串的ascii码,chr()函数获取ascii码对应的单字符字符串')
print(ord('A')) # 65
print(chr(65)) # A
print(chr(ord('a'))) # a


【6.5】使用 pyperclip模块 复制粘贴字符串

1)pyperclip模块有copy与paste函数,用于向计算机的剪贴板发送文本或接收文本

print('\n\n===pyperclip模块有copy与paste函数,用于向计算机的剪贴板发送文本或接收文本')
pyperclip.copy('hello, world')
print('pyperclip.paste() = ' + pyperclip.paste())  # pyperclip.paste() = hello, world


【6.6】项目:使用多剪贴板自动回复消息

1)输入关键字,python程序根据关键字查找对应详情文本,并复制到剪切板; 然后我们按下 ctrl+v 即可粘贴;

import pyperclip
import sys

textDict01 = {'agree': '''yes, i agree your idea'''
              , 'busy': '''sorry, system is busy now'''
              , 'disagree': '''i am sorry, i can't do it'''
}

if len(sys.argv) < 2:
    print('参数个数不少于2个')
    sys.exit()

keyPhrase = sys.argv[1]

if keyPhrase in textDict01:
    pyperclip.copy(textDict01[keyPhrase])
    print('detail for ' + keyPhrase + ' copied to clipboard')
else:
    print('there is no detail for ' + keyPhrase)

【制作批处理文件】myClip.bat

@py.exe D:\studynote\00-ai-llm\workbench\PythonBasicStudy\chapter06_stropr\test06_clipboard.py %*
@pause

【运行效果】

在这里插入图片描述

【粘贴效果】

yes, i agree your idea



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值