@zhangyu756897669
2017-08-30T15:42:52.000000Z
字数 3340
阅读 563
python官方文档
我们来看看Python代码中编写,打印和访问字符串的一些方法。
在Python代码中键入字符串值是非常简单的:它们以单引号开头和结尾。但是那么你怎么能在字符串中使用引号呢?打字“'That is Alice's cat.'”。将无法工作,因为Python认为字符串在Alice之后结束,其余的(“cat”)是无效的Python代码。幸运的是,有多种方式键入字符串。
spam = "That is Alice's cat."
转义字符允许您使用否则不可能放入字符串的字符。转义字符由反斜杠(\)组成,后跟要添加到字符串的字符。 (尽管由两个角色组成,通常被称为单个转义字符。)
例如,单引号的转义字符是\'。您可以使用以单引号开头和结尾的字符串。
spam = 'Say hi to Bob\'s mother.'
Python知道,由于Bob\'s
的单引号有一个反斜杠,它不是一个单引号意味着结束字符串值。转义字符\'和\“可以分别将单引号和双引号放在字符串中。
下表列出了可以使用的转义字符。
符号 | 含义 |
---|---|
\' | 单引号 |
\" | 双引号 |
\t | 标签 |
\n | 换行 |
\ | 反斜杠 |
print("Hello there!\nHow are you?\nI\'m doing fine.")
Hello there!
How are you?
I'm doing fine.
print(r'That is Carol\'s cat.')
That is Carol\'s cat.
print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')
Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob
print('Dear Alice,\n\nEve\'s cat has been arrested for catnapping, cat burglary, and extortion.\n\nSincerely,\nBob')
"""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 what the spam() function does."""
print('Hello!')
' H e l l o w o r l d ! '
0 1 2 3 4 5 6 7 8 9 10 11
spam = 'Hello world!'
spam[4]
'o'
spam[0:5]
'Hello'
spam[6:]
'world!'
spam = 'Hello world!'
fizz = spam[0:5]
fizz
'Hello'
通过将生成的子字符串切片并存储在另一个变量中,您可以同时拥有整个字符串和子字符串,方便快捷访问。
'Hello' in 'Hello World'
True
'HELLO' in 'Hello World'
False
'' in 'spam'
True
upper(),lower(),isupper()和islower()String Methods
spam = 'Hello world!'
spam = spam.upper()
spam
'HELLO WORLD!'
spam = spam.lower()
spam
hello world
请注意,这些方法不会更改字符串本身,而是返回新的字符串值。如果要更改原始字符串,则必须在字符串上调用upper()或lower(),然后将新字符串分配给存储原始文件的变量。这就是为什么你必须使用spam = spam.upper()来更改spam中的字符串,而不是简单的spam.upper()。 (这就像一个egg中含有的值10.写egg + 3不改变鸡蛋的价值,但 egg =egg + 3 会改变egg 的值)。
如果您需要进行不区分大小写的比较,则upper()和lower()方法是有帮助的。'great'和'GREat'彼此不相等。但是在下面的小程序中,用户是否输入“Great”,“GREAT”或“grEAT”并不重要,因为该字符串首先被转换为小。
print('How are you?')
feeling = input()
if feeling.lower() == 'great':
print('I feel great too.')
else:
print('I hope the rest of your day is good.')
How are you?
GREat
I feel great too.
spam = 'Hello world!'
spam.islower()
False
'HELLO'.isupper()
True
'abc12345'.islower()
Ture
'12345'.isupper()
False
'Hello'.upper()
HELLO
'Hello'.upper().lower()
hello
'Hello'.upper().lower().upper()
HELLO
'HELLO'.lower().islower()
True