[关闭]
@zhangyu756897669 2017-08-30T15:42:52.000000Z 字数 3340 阅读 563

python官方文档16.0

python官方文档


原始字符串和多行字符串

使用字符串

我们来看看Python代码中编写,打印和访问字符串的一些方法。

字符串文字

在Python代码中键入字符串值是非常简单的:它们以单引号开头和结尾。但是那么你怎么能在字符串中使用引号呢?打字“'That is Alice's cat.'”。将无法工作,因为Python认为字符串在Alice之后结束,其余的(“cat”)是无效的Python代码。幸运的是,有多种方式键入字符串。

双引号

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

转义字符

  1. spam = 'Say hi to Bob\'s mother.'
符号 含义
\' 单引号
\" 双引号
\t 标签
\n 换行
\ 反斜杠
  1. print("Hello there!\nHow are you?\nI\'m doing fine.")

Hello there!
How are you?
I'm doing fine.

原始字符串

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

That is Carol\'s cat.

具有三重引号的多行字符串

  1. print('''Dear Alice,
  2. Eve's cat has been arrested for catnapping, cat burglary, and extortion.
  3. Sincerely,
  4. Bob''')

Dear Alice,

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

Sincerely,
Bob

  1. print('Dear Alice,\n\nEve\'s cat has been arrested for catnapping, cat burglary, and extortion.\n\nSincerely,\nBob')

多行注释

  1. """This is a test Python program.
  2. Written by Al Sweigart al@inventwithpython.com
  3. This program was designed for Python 3, not Python 2.
  4. """
  5. def spam():
  6. """This is a multiline comment to help
  7. explain what the spam() function does."""
  8. print('Hello!')

索引和字符串切片

' H e l l o w o r l d ! '
0 1 2 3 4 5 6 7 8 9 10 11

  1. spam = 'Hello world!'
  1. spam[4]

'o'

  1. spam[0:5]

'Hello'

  1. spam[6:]

'world!'

  1. spam = 'Hello world!'
  2. fizz = spam[0:5]
  3. fizz

'Hello'

通过将生成的子字符串切片并存储在另一个变量中,您可以同时拥有整个字符串和子字符串,方便快捷访问。

运算符IN 与 NOT 中使用字符串

  1. 'Hello' in 'Hello World'

True

  1. 'HELLO' in 'Hello World'

False

  1. '' in 'spam'

True

字符串方法和pyperclip模块

upper(),lower(),isupper()和islower()String Methods

  1. spam = 'Hello world!'
  2. spam = spam.upper()
  3. spam

'HELLO WORLD!'

  1. spam = spam.lower()
  2. spam

hello world

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

How are you?
GREat
I feel great too.

  1. spam = 'Hello world!'
  2. spam.islower()

False

  1. 'HELLO'.isupper()

True

  1. 'abc12345'.islower()

Ture

  1. '12345'.isupper()

False

  1. 'Hello'.upper()

HELLO

  1. 'Hello'.upper().lower()

hello

  1. 'Hello'.upper().lower().upper()

HELLO

  1. 'HELLO'.lower().islower()

True

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注