python快速上手_第六章 字符串

处理字符串

字符串字面量

python中的字符串是以 单引号 ‘ 开始, 单引号结束 ’ 。 但是,如果字符串中有 单引号 ’ 怎么办?

有下面几种方法:

  • 双引号。 字符串使用双引号开始和结束。这样就可以在字符串中使用单引号了。

  • 转义字符 倒斜杠 \ 后面紧跟你要添加到字符串中的字符。 比如单引号的转义字符是 ’ .

    其他的转义字符

    ’ 单引号
    " 双引号
    \t 制表符
    \n 换行符
    \ 倒斜杠

比如下面的代码

>>> print('Hello there!\nHow are you?\nI\'m doing fine.')
Hello there!
How are you?
I'm doing fine.
  • 原始字符串, 在字符串开始的引号之前加上 r ,使它成为原始字符串。“原始字符串” 完全忽略所有的转义字符,打印出字符串中所有的倒斜杠。
>>> print(r'That is Carol\'s cat')
That is Carol\'s cat
用三重引号的多行字符串

可以用\n 转义字符将换行放入一个字符串,同样可以使用多行字符串,更简单一些。

多行字符串的起止是 3个 单引号或者 3个 双引号。三重引号之间的所有引号、制表符或换行,都被认为是字符串的一部分。Python的代码缩进不适用于多行字符串。

print('''Dear Alice,

Eve's cat has been arrested for catnapping.

Sincerely,
Bob
''')

打印为

Dear Alice,

Eve's cat has been arrested for catnapping.

Sincerely,
Bob
多行注释

#表示的是单行注释, 多行文本需要注释的时候常用多行注释 “”“注释的内容”“” 以三个单引号或者双引号开始,三个单引号或者三个双引号结束。比如下面的程序,可以正常打印出 hello.

"""Dear Alice,

Eve's cat has been arrested for catnapping.

Sincerely,
Bob"""


print('hello')
字符串下标和切片

字符串可以看作是一个列表.字符串的每个字符都是一个表项,都有下标值。

python中的切片和 java中的 substring(start,end)比较类似。都是包前不包后。

>>> spam = 'hello world!'
>>> spam[0]
'h'
>>> spam[4]
'o'
>>> spam[-1]
'!'
>>> spam[0-5]
'o'
>>> spam[0:5]
'hello'
>>> spam[:5]
'hello'
>>> spam[6:]
'world!'

字符串切片并没有修改原来的字符串,这点和Java中是一样的,字符串是不可变的;而是返回了一个新的字符串,我们可以把它记录到一个变量中。

>>> spam
'hello world!'
>>> newStr = spam[0:5]
>>> newStr
'hello'
in 和 not in

in 和 not in 操作符同样作用于字符串。 连接两个字符串,返回值为 True 或者 False. 判断第一个字符串是否在第二个字符串中(区分大小写)。

>>> spam = 'hello world!'
>>> 'hello' in spam
True
>>> 'Hello' in spam
False
>>> '' in spam
True
>>> 'wor' not in spam
False

有用的字符串方法

upper()、lower()、isupper() 和 islower()

upper() 和 lower()方法 是将字符串转换为对应的 大写或者小写。 在Java中,有 toUpperCase() 和 toLowerCase(),实现的功能都是一样的。

这两个方法调用会返回一个新的字符串,并不会修改字符串本身。如果想修改,可以通过赋值给原来的变量。如:spam = spam.upper().

>>> spam = 'Hello World'
>>> spam
'Hello World'
>>> spam.upper()
'HELLO WORLD'
>>> spam.lower()
'hello world'
>>> spam
'Hello World'
>>> spam = spam.upper()
>>> spam
'HELLO WORLD'

字符串是区分大小写的, 比如 ‘Great’ 同 ‘GREat’ 就不相等。 但如果需要做大小写无关的比较。那么就可以进行转换成 大写或者小写, 再做比较。

How are you ? 
Great
I feel great too
>>> 
How are you ? 
GReAt
I feel great too

字符串中,至少有一个字母。并且必须是全部大写或者小写, isupper()或者islower()才会返回True 否则返回False.

>>> spam = 'Hello world'
>>> spam.islower()
False
>>> spam.isupper()
False
>>> 'HELLO'.isupper()
True
>>> 'abc123'.islower()
True
>>> '123'.islower()
False

upper()和lower() 返回的是一个字符串,所以我们可以对字符串再进行操作,形成链式调用。

>>> spam = 'Hello world'
>>> spam.upper().islower()
False
>>> spam.upper()[0:5]
'HELLO'
isX字符串方法

除了 islower() 和 isupper()方法,还有以下常用的方法:

  • isalpha() 返回True, 如果字符串只包含字母,并且非空;
  • isalnum() 返回True, 如果字符串只包含字母和数字,并且非空;
  • isdecimal() 返回True,如果字符串只包含数字字符,并且非空;
  • isspace() 返回True, 如果字符串只包含空格、制表符和换行,并且非空;
  • istitle() 返回True, 如果字符串仅包含大写字母开头,后面都是小写字母的单词。
>>> 'hello'.isalpha()
True
>>> 'hello123'.isalpha()
False
>>> 'hello123'.isalnum()
True
>>> 'hello'.isalnum()
True
>>> '123'.isdecimal()
True
>>> ' '.isspace()
True
>>> ''.isspace()
False
>>> 'This is Title'.istitle()
False
>>> 'This Is Title'.istitle()
True

上面的方法,可以对用户输入进行校验。判断用户输入是否合乎要求。

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 have letters and numbers')

java 中对于条件的取反使用的是 ! 感叹号,放在布尔条件的前面; 而 python 中是在 布尔条件前面加 not。

字符串的 startswith() 和 endswith()

和java中的一样, 如果调用相应方法的字符串以参数传入的字符串 开始或者结束,就会返回True.

>>> 'Hello world'.startswith('Hello')
True
>>> 'Hello world'.endswith('ld')
True
>>> 'Hello world'.startswith('abc')
False
字符串方法 join() 和 split()

如果需要把一个字符串列表连接起来, 形成一个字符串, 那么就可以使用join()方法。join()方法在一个字符串上调用,参数是一个字符串列表。

>>> '.'.join(['a','b','c'])
'a.b.c'
>>> ' '.join(['My','name','is','mike'])
'My name is mike'

与join()相反, split()方法是分割一个字符串,返回一个列表。这个方法和java中的使用是一样的, 可以在方法中传入参数,作为分隔符。

>>> 'my name is mike'.split()
['my', 'name', 'is', 'mike']
>>> 'my/name/is/mike'.split()
['my/name/is/mike']
>>> 'my/name/is/mike'.split('/')
['my', 'name', 'is', 'mike']

一个比较常见的用法是,使用\n分割多行字符串。

>>> '''abc
def
hig
lmn
'''.split('\n')
['abc', 'def', 'hig', 'lmn', '']
用 rjust()、ljust() 和 center()对齐文本

即希望是左对齐,还是右对齐或者中间对齐。 第一个参数是一个整数,用于对齐字符串。比如 ‘Hello’.rjust(10) 本身字符长度为5个字符,参数为10,右对齐, 那么会在左边加入5个空格来填充。

>>> 'hello'.rjust(10)
'     hello'
>>> 'hello world'.rjust(20)
'         hello world'
>>> 'Hello'.rjust(20)
'               Hello'
>>> 'world'.ljust(10)
'world     '

第二个参数,传入一个字符串,表示用什么来填充。

>>> 'hello'.rjust(10,'*')
'*****hello'
>>> 'Hello'.rjust(20,'-')
'---------------Hello'

下面是一个对物品的数量的打印:

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

picnicItems = {'sandwiches':4,'apples':12,'cups':10,'cookies':8000}

printPicnic(picnicItems,12,5)
printPicnic(picnicItems,20,6)

打印如下:

---PICNIC ITEMS--
sandwiches..4    
apples......12   
cups........10   
cookies.....8000 
-------PICNIC ITEMS-------
sandwiches..........4     
apples..............12    
cups................10    
cookies.............8000  
strip()、rstrip()和lstrip() 删除空白字符串

删除两边、右边、左边的空白字符(空格、制表符和换行符)。将返回一个新的字符串。

>>> '  helloworl d  '.strip()
'helloworl d'
>>> '  helloworl d  '.rstrip()
'  helloworl d'
>>> '  helloworl d  '.lstrip()
'helloworl d  '

可以给方法内传入一个字符串,用来说明哪些字符需要被删除。

>>> 'spammsaphellospmppmsa'.strip('samp')
'hello'
>>> 'spammsaphellospmppmsa'.lstrip('samp')
'hellospmppmsa'
>>> 'spammsaphellospmppmsa'.rstrip('samp')
'spammsaphello'

上面的的例子中 ‘s’、‘a’、‘m’、‘p’ 这些两边的字符会被删除。 ‘samp’ 或者 ‘spma’ 都不重要。(区分大小写)

用pyperclip 模块拷贝粘贴字符串

pyperclip模块是第三方模块,需要安装。 该模块有 copy()和paste()函数, 可以向计算机的剪贴板发送文本,或从它接收文本。将程序的输出发送到剪贴板,使它很容易粘贴到邮件、文字处理系统等。

>>> import pyperclip
>>> pyperclip.copy('hello world')
>>> pyperclip.paste()
'hello world'

其他第三方程序 或者系统调用 剪贴板 复制的内容。 我们这边都可以直接调用 paste()方法获取到。

项目:口令保管箱

#!/usr/bin/env python3

# an insecure password locker program

PASSWORDS = {'email':'abc123','blog':'abc456','luggage':'123456'}

import sys
import pyperclip

if len(sys.argv) < 2:
    print('Usage: python six_program [account] - copy account password')
    sys.exit()

print('arg[0] '+sys.argv[0] + ' arg[1] '+sys.argv[1])
account = sys.argv[1]

if account in PASSWORDS:
    pyperclip.copy(PASSWORDS[account])
    print('your '+account+' has copied to the clipboard')
else:
    print('These is no account named : '+account)

项目:在Wiki标记中添加无序列表

#!/usr/bin/env python3

import pyperclip

text = pyperclip.paste()

# then add star to lines

lines = text.split('\n')

for i in range(len(lines)):
    lines[i] = '* '+lines[i]


newText = '\n'.join(lines)

pyperclip.copy(newText)

实践项目 - 表格打印


tableData = [['apples','oranges','cherries','banana'],
             ['Alice','Bob','Carol','David'],
             ['dogs','cats','moose','goose']]

def loadColWidth(tabData):
    colWithsTemp = [0]*len(tabData)
    
    for i in range(len(tabData)):
        lastStuffLen = 0
        for stuff in tabData[i]:
            if lastStuffLen < len(stuff):
                lastStuffLen = len(stuff)

        print('i'+str(i))
        colWithsTemp[i] = lastStuffLen
    return colWithsTemp

def printTables(tabData,colWidths):
    for x in range(len(tabData[0])):

        for y in range(len(tabData)):
            if y == 0:
                print(tabData[y][x].rjust(colWidths[y]),end=' ')
            else:
                print(tabData[y][x].ljust(colWidths[y]),end=' ')

        print()
    
    

colWidths =  loadColWidth(tableData)

print(colWidths)

printTables(tableData,colWidths)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值