python字符串

字符串下标和切片

和列表类似

字符串的 in 和 not in

和列表类似

字符串的方法

  • upper():将字符串转换为大写

  • lowper():将字符串转换为小写

  • isupper():字符串是否全为大写

  • islowper():字符串是否全为小写

  • isalpha():字符串是否只包含字母,并且非空

  • isalnum():字符串是否只包含字母和数字,并且非空

  • isdecimal():字符串是否只包含数字字符,并且非空

  • isspace():字符串是否只包含空格、制表符和换行,并且非空

  • istitle():字符串是否仅包含以大写字母开头、后面都是小写,并且非空

startswith() 和 endswith()

mystr = 'Hello world!'
mystr.startswith('He')
True
mystr.startswith('he')
False
mystr.endswith('ld!')
True
mystr.endswith('Hello world!')
True

join() 和 split()

fruits = ['apple', 'banana', 'orange', 'pear']
newStr = ','.join(fruits) #用逗号将列表中的元素连接起来
print(newStr)
apple,banana,orange,pear
','.join(['apple', 'banana', 'orange', 'pear'])
'apple,banana,orange,pear'
nStr = 'Everthing will be fine.'
nStrx = nStr.split() #默认情况下,split()是按照空白符将字符串分割,并以列表的形式返回
print(nStrx)
['Everthing', 'will', 'be', 'fine.']
nStr = 'EverthingABCwillABCbeABCfine.'
nStrx = nStr.split('ABC') #按照指定的字符分割
print(nStrx)
['Everthing', 'will', 'be', 'fine.']
# 一个常用的 split() 用法,是按照换行符分割多行字符串
message = '''Hello zhong,
how are you?

what are you doing now?
'''
message.split('\n')

rjust() 、ljust() 和 center() 对齐文本

方法名(要输出的文本长度,'填充的字符') #默认用空白填充

'hello'.rjust(10)
'     hello'
'hello'.rjust(3)
'hello'
'hello'.rjust(20)
'               hello'
'hello'.rjust(15, '*')
'**********hello'
'hello'.ljust(10)
'hello     '
'hello'.ljust(10, '#')
'hello#####'
'hello'.center(10, '=')
'==hello==='
'hello'.center(15, '#')
'#####hello#####'
def printPicnic(itemsDic, leftWidth, rightWidth):
    print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))
    for k, v in itemsDic.items():
        print(k.ljust(leftWidth, '-') + str(v).rjust(rightWidth))
    
picnicItems = {'apple':5, 'banaba':3, 'organce':4, 'pear':8}

printPicnic(picnicItems, 12, 5)
printPicnic(picnicItems, 20, 0)
---PICNIC ITEMS--
apple-------    5
banaba------    3
organce-----    4
pear--------    8
----PICNIC ITEMS----
apple---------------5
banaba--------------3
organce-------------4
pear----------------8

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

myStr = '          Hello world!    '
myStr.strip() #删除字符串开头和末尾(左右两边)的空白字符
'Hello world!'
myStr = '          Hello world!    '
myStr.rstrip() #删除字符串右边的空白字符
'          Hello world!'
myStr = '          Hello world!    '
myStr.lstrip() #删除字符串左边边的空白字符
'Hello world!    '

pyperclip 模块下的 copy() 和 paster()

复制和粘贴字符串

import pyperclip

pyperclip.copy('Hello world!')
pyperclip.paster()
posted @ 2020-12-30 12:56  你是真的菜啊  阅读(96)  评论(0编辑  收藏  举报