Python新手学习(五):字符串操作

本文介绍了Python中的字符串处理、转义字符、原始字符串、多行字符串、注释、索引和切片、字符串操作、格式化方法,以及使用pyperclip模块进行剪贴板操作和在Wiki标记中添加无序列表。此外,还展示了如何将英语转换为PigLatin。
摘要由CSDN通过智能技术生成

6.字符串操作
  剪贴板和文本格式化。
  1)处理字符串
    字符串字面量:单引号或者双引号,一般是单引号,
    双引号:如果字符串中有单引号,则用双引号括住。
    转义字符:如果内容既有单引号又有双引号,则用转义符,即“\”
      转义包括 \’ \” \t \n \\
    原始字符串:前缀加r
    多行字符串:三重引号
    多行注释: 三重双引号 
    测试程序:test_601.py

"""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 waht the spam() function does."""
    print ('Hello!')

spam()

    字符串索引和切片:可将字符串改成一个不可变的列表。
    字符串的包含操作:in 和 not in
2)字符串插入填充其它字符串
    ‘str %s str’ % vstr
     f’strstr{vl} str str’ 前缀加f
3)字符串方法
    upper(),lower(),isupper(),islower()
    测试程序 test_602.py

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

    isalpha(),isalnum(),isdecimal(),isspace(),istitle()
    测试程序 test_603.py

while True:
    print('Enter you age:')
    age = input()
    if age.isdecimal():
        break
    print('Please enter a number for you 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')
    

    startswith(),endswith() 开始于 ,结束于
    join(),split()  联接和分割
    partition() 分隔字符串为元组的三个项
    rjust(),ljust(),center() 填充字符串前、后缀形在固定场宽。
    测试程序 test_604.py

def printPicnic(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':8000}
printPicnic(picnicItems,12,5)
printPicnic(picnicItems,20,6)

    strip(),lstrip(),rstrip() 删除空白字符
4)ord()和chr() 字符的数值
5)pyperclip模块
    复制粘贴字符串
    实现系统级复制/粘贴功能
    pip install pyperclip
6)项目:多剪贴板自动回复消息
    测试程序:test_605.py 

#! python3
# mclip.py - A multi-clipboard program.

TEXT = {'agree':"""Yes.I agree. That sounds fine to me.""",
        'busy':"""Sorry,cn we do this later this week or next week?""",
        'upsell':"""Would you consider making this a monthly donation?"""}

import sys,pyperclip
if len(sys.argv) < 2:
    print('Usage: python mclip.py [keyphrase] copy phrase text')
    sys.exit()

keyphrase = sys.argv[1]     # first command line arg is the keyphrase

if keyphrase in TEXT:
    pyperclip.copy(TEXT[keyphrase])
    print('Text for ' + keyphrase + ' copyied to clipboard.')
else:
    print('There is no text for ' + keyphrase)

7)项目:在Wiki标记中添加无序列表
    test_606.py

#! python3
# bulletPointAdder.py - Adds Wikipedia bullet points to the start
# of each line of text on the clipboard.

import pyperclip
text = pyperclip.paste()
print('BFR:\n' + text)

# Separate lins and add stars.
lines= text.split('\n')
for i in range(len(lines)):     # loop through all indexes in the "lines" list
    lines[i] = '*' + lines[i]   # add start to each string in "lines" list

text = '\n'.join(lines)

print('Add:\n' + text)
pyperclip.copy(text)

8)小程序:pig latin
    test_607.py
 

# English to Pig Latin
print('Enter the English message to translate into Pig Latin:')
message = input()

VOWELS = ('a','e','i','o','u','y')

pigLatin = []       # A list of the words in Pig latin.
for word in message.split():
    # Separate the non-letters at the start of this word:
    prefixNonLetters = ''
    while len(word) > 0 and not word[0].isalpha():
        prefixNonLetters += word[0]
        word = word[1:]
    if len(word) == 0:
        pigLatin.append(prefixNonLetters)
        continue

    # Separate the non-letters at the end of this word:
    suffixNonLetters = ''
    while not word[-1].isalpha():
        suffixNonLetters += word[-1]
        word = word[:-1]
    
    # Remember if the word was in uppercase or title case.
    wasUpper = word.isupper()
    wasTitle = word.istitle()

    word = word.lower()     # Make the word lowercase for translation.

    # Separate the consonants at the start of this word:
    prefixConsonants = ''
    while len(word) > 0 and not word[0] in VOWELS:
        prefixConsonants += word[0]
        word = word[1:]

    # Add the Pig Latin ending to the word:
    if prefixConsonants != '':
        word += prefixConsonants + 'ay'
    else:
        word += 'yay'

    # Set the word back to uppercse or title case:
    if wasUpper:
        word = word.upper()
    if wasTitle:
        word = word.title()

    # Add the non-Letters back to the start or end of the word.
    pigLatin.append(prefixNonLetters +word + suffixNonLetters)

# Join all the words back together into a single string:
print(' '.join(pigLatin))

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值