python--字符串操作

双引号

>>> spam = "That is Alice 's cat."

转义字符

>>> spam = 'Say hi to Bob \'s mother'
>>> spam
"Say hi to Bob 's mother"

这里写图片描述

>>> print("Hello there!\n How are you ? \n I\'m doung fine.")
Hello there!
 How are you ? 
 I'm doung fine.

原始字符串

>>> print(r'That is Carol \'s cat. ')
That is Carol \'s cat. 

用三重引号的多行字符串




print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, adn extortion.
Sincerely,
Bob''')

这里写图片描述


多行注释

""" This is a test python program.
Written by Al Sweigart al@inventwithpython.com

This program was designed for python 3, not python 2.
"""

def spam():
    """This is a multiline comment to help
    explain what the spam() function does."""
    print('hello!')

spam()


字符串下标和切片

>>> spam = 'Hello world!'
>>> spam[0]
'H'
>>> spam[4]
'o'
>>> spam[-1]
'!'
>>> spam[0:5]
'Hello'
>>> spam[:5]
'Hello'
>>> spam[6:]
'world!'
>>> spam = 'Hello word!'
>>> fizz = spam[0:5]
>>> fizz
'Hello'

字符串的in 和not in 操作符

>>> spam = 'Hello world!'
>>> spam[0]
'H'
>>> spam[4]
'o'
>>> spam[-1]
'!'
>>> spam[0:5]
'Hello'
>>> spam[:5]
'Hello'
>>> spam[6:]
'world!'
>>> spam = 'Hello word!'
>>> fizz = spam[0:5]
>>> fizz
'Hello'
>>> 'Hello' in 'Hello World'
True
>>> 'Hello' in 'Hello'
True
>>> 'HELLO' in 'Hello'
False

有用的字符串方法

一些字符串方法会分析字符串,或生成转变过的字符串。


字符串方法upper()、lower()、isupper()和islower()

upper()和lower()字符串方法返回一个新字符串,其中原字符串的所有字母都被相应的转换为大写或小写。

>>> spam = 'Hello world!'
>>> spam = spam.upper()
>>> spam
'HELLO WORLD!'
>>> spam = spam.islower()
>>> spam
False



print('How are you ?')
feeling = input()
if feeling.lower() == 'great':
    print('I feel great too')
else:
    print('I hope the rest of your day is good; ')

这里写图片描述

>>> spam = 'Hello world!'
>>> spam = spam.upper()
>>> spam
'HELLO WORLD!'
>>> spam = spam.islower()
>>> spam
False
>>> spam = 'Hello world ! '

>>> spam.islower()
False
>>> 'Hello'.upper()
'HELLO'
>>> 'Hello'.upper().lower()
'hello'
>>> 'Hello'.upper().lower().upper()
'HELLO'
>>> 'HELLO'.lower()
'hello'
>>> 'HELLO'.lower().islower()

isX字符串方法

isalpha() 如果字符串只包含字母,并且非空
isalnum() 如果字符串只包含字母和数字,并且非空
isdecimal() 如果字符串只包含数字字符,并且非空
isspace() 如果字符串只包含空格、制表符和换行,并且非空
istitle() 如果字符串仅包含以大写字母开头、后面都是小写字母的单词

>>> 'hello'.isalpha()
True
>>> 'hello123'.isalpha()
False
>>> 'hello123'.isalnum()
True
>>> 'hello'.isalnum()
True
>>> '123'.isdecimal()
True
>>> ' '.isspace()
True
>>> 'This Is Title Case'.istitle()
True
>>> 'This Is Case 123'.istitle()
True
>>> 'This Is not Title Case'.istitle()
False
>>> 'This Is NOT Title Case Either'.istitle()
False

如果需要验证用户输入,isX字符串方法是有用的。下面的程序反复询问用户年龄和口令,直到它们提供有效的输入。

while True:
    print('Enter your age:')
    age = input()
    if age.isdecimal():
        break
    print('Please enter a number for your age.')

while True:
    print('Select a new password (letters and numbers only):')
    password = input()
    if password.isalnum():
        break
    print('Passwords can only havade letters and numbers.')

这里写图片描述


字符串方法startswith()和endswith()

>>> 'Hello world!'.startswith('Hello')
True
>>> 'Hello world!'.endswith('world!')
True
>>> 'abc123'.startswith('abcdef')
False
>>> 'abc123'.endswith('12')
False
>>> 'Hello world!'.startswith('Hello world1')
False

字符串方法join()和split()

如果有一个字符串列表,需要将它们连接起来,成为一个单独的字符串,join()方法就很有用。join()方法在一个字符串上调用,参数是一个字符串列表,返回一个字符串。返回的字符串由传入的列表中每个字符串连接而成。

>>> ','.join(['cats','rsts','bats'])
'cats,rsts,bats'
>>> ' '.join(['My','name','is','Simon'])
'My name is Simon'
>>> 'ABC'.join(['My','name','is','Simon'])
'MyABCnameABCisABCSimon'

调用join()方法的字符串,被插入到列表参数中每个字符串的中间。
记住join()方法是针对一个字符串而调用的,并且传入一个列表值(很容易不小心用其他的方式调用它)。split()方法做的事情正好相反:它针对一个字符串调用,返回一个字符串列表。

>>> 'My name is Simon'.split()
['My', 'name', 'is', 'Simon']

默认情况下,字符串’My name is Simon’按照各种空白字符分割,诸如空格、制表符或换行符。这些空白字符不包含在返回列表的字符串中。也可以向split()方法传入一个分割字符串,指定它按照不同的字符串分割。

>>> 'MyABCnameABCisABCSimon'.split('ABC')
['My', 'name', 'is', 'Simon']
>>> 'My name is Simon'.split('m')
['My na', 'e is Si', 'on']

一个常见的split()用法,是按照换行符分割多行字符串。

>>> spam = """Dear Alice,"""
>>> spam = """ """
>>> spam = """ Dear Alice,
... How have you been? I am fine.
... Ther is a container in the fridge
... that is labeled "milk Experiment".
... Please do not drink it.
... Sincerely,
... Bob"""
>>> spam.split('\n')
[' Dear Alice,', 'How have you been? I am fine.', 'Ther is a container in the fridge', 'that is labeled "milk Experiment".', 'Please do not drink it.', 'Sincerely,', 'Bob']

向split()方法传入参数’\n’,我们按照换行符分割变量中存储的多行字符串,返回列表中的每个表项,对应于字符串中的一行。


用rjust()、ljust()和center()方法对齐文本

rjust()和ljust()字符串方法返回调用它们的字符串的填充版本,通过插入空格来对齐文本。这两个方法的第一个参数是一个整数长度,用于对齐字符串。

>>> 'Hello'.rjust(10)
'     Hello'
>>> 'Hello'.rjust(20)
'               Hello'
>>> 'Hello World'.rjust(20)
'         Hello World'
>>> 'Hello'.ljust(10)
'Hello     '

‘Hello’.rjust(10)是说我们希望右对齐,将’Hello’放在一个长度为10的字符串中。
‘Hello’有5个字符,所以左边会加上5个空格,得到一个10个字符的字符串,实现’Hello’右对齐。
rjust()和ljust()方法的第二个可选参数将指定一个填充字符,取代空格字符。

>>> 'Hello'.rjust(20,'*')
'***************Hello'
>>> 'Hello'.ljust(20,'-')
'Hello---------------'

center()字符串方法与ljust()与 rjust()类似,但它让文本居中,而不是左对齐或右对齐。

>>> 'Hello'.center(20)
'       Hello        '
>>> 'Hello'.center(20,'=')
'=======Hello========'

如果需要打印表格式数据,留出正确的空格,这些方法就特别有用。



def prinPicnic(itemsDict, leftWidth, rightWidth):
    print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))
    for k, v in itemsDict.items():
        print(k.ljust(leftWidth,'.') + str(v).rjust(rightWidth))

picnicItems = {'sandwiches':4, 'apples':12, 'cups':4, 'cookies':3000}
prinPicnic(picnicItems, 12, 5)
prinPicnic(picnicItems, 15, 6)

在这个程序中,定义了printPicnic()方法,它接受一个信息字典,并利用center()、ljust()和rjust(),以一种干净对齐的表格形式显示这些信息。
我们传递给printPicnic()的字典是picnicItems。在picnicItems中,有4个三明治、12个苹果、4个杯子和3000块饼干。将这些信息组织成两行,表项的名字在左边,数量在右边。
要做到这一点,就需要决定左列和右列的宽度。与字典一起,我们将這些值传递给printPicnic()。
printPicnic()接受一个字典,一个leftWidth表示表的左列宽度,一个rightWidth表示表的右列宽度。它打印出标题PICNIC ITEMS,在表上方居中。然后它遍历字典,每行打印一个键-值对。键左对齐,填充句号。值右对齐,填充空格。
在定义printPicnic()后,我们定义了字典picnicItems,并调用printPicnic()两次,传入不同的表左右列宽度。
运行该程序,野餐用品就会显示两次。第一次左列宽度是12个字符,右列宽度是5个字符。第二次它们分别是20个和6个字符。
这里写图片描述

利用rjust()和ljust()、center()让你确保字符串整齐对齐,即使你不清楚字符串有多少字符。


用strip()、rstrip()和lstrip()删除空白字符

有时候你希望删除字符串左边、右边或两边的空白字符(空格、制表符和换行符)。strip()字符串方法将返回一个新的字符串,它的开头或末尾都没有空白字符。
lstrip()和rstrip()方法将相应删除左边或右边的空白字符。

>>> spam = ' Hello Word '
>>> spam.strip()
'Hello Word'
>>> spam.lstrip()
'Hello Word '
>>> spam.rstrip()
' Hello Word'

有一个可选的字符串参数,指定两边的哪些字符应该删除。

>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
>>> spam.strip('ampS')
'BaconSpamEggs'

向strip()方法传入参数’ampS’,告诉它在变量中存储的字符串两端,删除出现的a、m、p和大写的S。传入strip()方法的字符串中,字符的顺序并不重要:strip(‘ampS’)做的事情和strip(‘Spam)一样。


用pyperclip模块拷贝粘贴字符串

pyperclip模块有copy()和paste()函数,可以向计算机的剪贴板发送文本,或从它接收文本。将程序的输出发送到剪贴板,使它很容易粘贴到邮件、文字处理程序或其他软件中。pyperclip模块不是python自带的。要安装它,必须安装第三方模块。

>>> import pyperclip
>>> pyperclip.copy('Hello word!')
>>> pyperclip.paste()
'Hello word!'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值