欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python string

程序员文章站 2022-05-02 22:17:53
...

raw strings

在字符串前面加r,将忽略所有的逃逸字符

print(r'That is Carol\'s cat.')
# 输出为
That is Carol\'s cat.

mulitline strings with triple quotes

用三个单引号或者三个双引号,可以引用多行字符串

print('''Dear Alice,

Eve's cat has been arrested for catnapping, cat burglary, and extortion.

Sincerely,
Bob''')

多行注释

"""This is a test Python program.
Written by [email protected]

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

def spam():
    """This s a multipline comment to help
       explain what the spam() function doese."""
    print('Hello!')


spam()

indexing and slicing strings

spam = 'Hello world!'
print(spam[0])
print(spam[4])
print(spam[4:])
print(spam[-1])
print(spam[:5])
print(spam)

The isX String methods

  • isalpha() 如果string只包含字母,并且没有空格
  • isalnum() 如果string只包含字母和数字,并且没有空格
  • isdecimal() 如果string只包含数字,并且没有空格
  • isspace() 如果string 只包含spaces, tabs 和 newlines. and is not blank
  • istitle() 如果string包含的单词的第一个字母都是大写。

startswith() 和 endswith()

判断字符串是否以给定的字符串作为还是或结束。

The join() and split() String Methods

join 以给定的字符或者字符串,讲数值里面的字符串链接起来

spam = ['cats', 'rats', 'bats']
print(', '.join(spam))

spam = ['My', 'name', 'is', 'Huxing']
print(' '.join(spam))

print('ABC'.join(spam))

split 以给定的字符或者字符串将目标字符串拆分成一个数组。如果不指定字符串,默认会易空格作为拆分标识。

spam = 'These white space characters are not included in the strings in the returned list.'
print(spam.split())

# 输出内容为
['These', 'white', 'space', 'characters', 'are', 'not', 'included', 'in', 'the', 'strings', 'in', 'the', 'returned', 'list.']

Justifying Text with rjust(), ljust(), and center()

spam = 'Hello'
print(spam.rjust(10))
print(spam.rjust(20))

spam = 'Hello World'
print(spam.rjust(20))
print(spam.ljust(10))

print(spam.rjust(20,'*'))
print(spam.ljust(20,'-'))

print(spam.center(20))
print(spam.center(20, '='))

# 输出的内容是
     Hello
               Hello
         Hello World
Hello World
*********Hello World
Hello World---------
    Hello World     
====Hello World=====

打印菜单

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)


# 输出内容是
---PICNIC ITEMS--
cups........    4
sandwiches..    4
cookies..... 8000
apples......   12
-------PICNIC ITEMS-------
cups................     4
sandwiches..........     4
cookies.............  8000
apples..............    12

removing whitespaces with strip(), rstrip(), and lstrip()

  • strip() will return a new string without any whitespace characters at the beginning or end.
  • lstrip() remove whitespace characters from the left ends.
  • rstrip() remove whitespace characters from the right ends.
spam = '     Hello World     '
print(spam.strip())
print(spam.lstrip())
print(spam.rstrip())

spam = 'SpamSpamBaconSpamEggsSpamSpam'
print(spam.strip('ampS')) #移除字符串中以a m p 或者 S 开始或结束的部分

# 输出内容是
Hello World
Hello World     
     Hello World
BaconSpamEggs

pyperclip  将字符串弄到粘贴板上

# 先安装pip
sudo apt-get install python3-pip
# 再安装 pyperclip module
sudo pip3 install pyperclip
# 安装依赖
sudo apt install xsel

代码如下

import pyperclip
pyperclip.copy('Hello world!')
pyperclip.paste()

粘贴板文字处理

从网上拷贝一段文字在粘贴板上,然后运行程序,再在另外一个地方粘贴

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

import pyperclip
text = pyperclip.paste()

# TODO: Separete lines and add starts.
text_array = text.split('\n')
start_text = []
for line in text_array:
    start_text.append('* ' + line)
past_text = '\n'.join(start_text)      

pyperclip.copy(past_text)



### 书里面给的答案
#! /usr/bin/python3
import pyperclip
text = pyperclip.paste()

# Separete lines and add stars.
lines = text.split('\n')
for i in range(len(lines)):  # loop through all indexes for "lines" list
    lines[i] = '* ' + lines[i] # add star to each string in "lines" list
text = '\n'.join(lines)
pyperclip.copy(text)

Table Printer

#! /usr/bin/python3

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

def printTable(tableData):
    max_width = []
    for i in range(len(tableData)):
       max_width.append(0)
       for j in range(len(tableData[i])):   
          word = tableData[i][j]
          if len(word) > max_width[i]:
               max_width[i] = len(word) 
    for j in range(len(tableData[0])):
        for i in range(len(tableData)):
            word = tableData[i][j]
            print(word.rjust(max_width[i]), end=' ')  
        print('')


printTable(tableData)

输出内容如下

  apples Alice  dogs 
 oranges   Bob  cats 
cherries Carol moose 
  banana David goose 
相关标签: pythong string