Python notes 0004: Strings

本文介绍了计算机科学中字符串的基本概念,着重讲解了在Python中如何操作字符串,包括直接输入命令提示符、使用字符串字面量、不同类型(如str)以及实践中的常见操作,如拼接、索引和切片。通过实例演示,展示了字符串常量的不同写法和内置函数的应用。
摘要由CSDN通过智能技术生成

1 What is strings?

1.1 Definition in computer science

In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation). A string is generally considered as a data type and is often implemented as an array data structure of bytes (or words) that stores a sequence of elements, typically characters, using some character encoding. String may also denote more general arrays or other sequence (or list) data types and structures.
A string

1.2 Definition in Python

String is an immutable data type in Python, which is generally used by users to express the human language that they want to transmit or store.

2 How to manipulate strings in Python?

2.1 Write at a command prompt

①Open cmd.exe. (You can find the method to open it in Python notes 0001: Computer.)
②Enter python to enter C:\WINDOWS\system32\cmd.exe - python
(The version of python I use is Python 3.7.9).
Note: The following is a demonstration of the use of strings. In order to make it easier for everyone to watch, PewerShell-style code blocks and step-by-step code are used, all of which are from the official website. Go to the official documentation(Python 3.7). You can go to the corresponding version content by changing the version number in URL.

2.2 Usage (from the official website)

  • Strings can be expressed in several ways which can be enclosed in single quotes ('...') or double quotes ("...") with the same result. \ can be used to escape quotes:
Microsoft Windows [Version 10.0.19042.868]
(c) 2020 Microsoft Corporation. All rights reserved.

C:\Users\Administrator>python
Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
  • Note: the following sections will be omitted in the following demos:
Microsoft Windows [Version 10.0.19042.868]
(c) 2020 Microsoft Corporation. All rights reserved.
C:\Users\Administrator>python
Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
  • In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with backslashes. While this might sometimes look different from the input (the enclosing quotes could change), the two strings are equivalent. The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes. The print() function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters:
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print('"Isn\'t," they said.')
"Isn't," they said.
>>> s = 'First line.\nSecond line.'  # \n means newline
>>> s  # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s)  # with print(), \n produces a new line
First line.
Second line.
  • If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:
>>> print('C:\some\name')  # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name')  # note the r before the quote
C:\some\name
  • String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. The following example:
>>> print("""\
... Usage: thingy [OPTIONS]
...      -h                        Display this usage message
...      -H hostname               Hostname to connect to
... """) # produces the following output (note that the initial newline is not included):
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
  • Strings can be concatenated (glued together) with the + operator, and repeated with *:
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
  • Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.
>>> 'Py' 'thon'
'Python'
  • This feature is particularly useful when you want to break long strings:
>>> text = ('Put several strings within parentheses '
...         'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
  • This only works with two literals though, not with variables or expressions:
>>> prefix = 'Py'
>>> prefix 'thon'  # can't concatenate a variable and a string literal
  File "<stdin>", line 1
    prefix 'thon'
                ^
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
  File "<stdin>", line 1
    ('un' * 3) 'ium'
                   ^
SyntaxError: invalid syntax
  • If you want to concatenate variables or a variable and a literal, use +:
>>> prefix + 'thon'
'Python'
  • Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:
>>> word = 'Python'
>>> word[0]  # character in position 0
'P'
>>> word[5]  # character in position 5
'n'
  • Indices may also be negative numbers, to start counting from the right:
>>> word = 'Python'
>>> word[-1]  # last character
'n'
>>> word[-2]  # second-last character
'o'
>>> word[-6]
'P'
  • Note that since -0 is the same as 0, negative indices start from -1.
  • In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring:
>>> word = 'Python'
>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'
  • Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s:
>>> word = 'Python'
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
  • Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.
>>> word = 'Python'
>>> word[:2]   # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:]   # characters from position 4 (included) to the end
'on'
>>> word[-2:]  # characters from the second-last (included) to the end
'on'
  • One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:
    Slices of strings
  • The first row of numbers gives the position of the indices 0…6 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j, respectively.
  • For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of word[1:3] is 2.
  • Attempting to use an index that is too large will result in an error:
>>> word[42]  # the word only has 6 characters
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
  • However, out of range slice indexes are handled gracefully when used for slicing:
>>> word[4:42]
'on'
>>> word[42:]
''
  • Python strings cannot be changed — they are immutable. Therefore, assigning to an indexed position in the string results in an error:
>>> word[0] = 'J'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
  • If you need a different string, you should create a new one:
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'
  • The built-in function len() returns the length of a string:
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

2.3 Text Sequence Type — str

Textual data in Python is handled with str objects, or strings. Strings are immutable sequences of Unicode code points. String literals are written in a variety of ways:

  • Single quotes: 'allows embedded "double" quotes'
  • Double quotes: "allows embedded 'single' quotes".
  • Triple quoted: '''Three single quotes''', """Three double quotes"""

Triple quoted strings may span multiple lines - all associated whitespace will be included in the string literal.
String literals that are part of a single expression and have only whitespace between them will be implicitly converted to a single string literal. That is, ("spam " "eggs") == "spam eggs".
See String and Bytes literals for more about the various forms of string literal, including supported escape sequences, and the r (“raw”) prefix that disables most escape sequence processing.
Strings may also be created from other objects using the str constructor.
Since there is no separate “character” type, indexing a string produces strings of length 1. That is, for a non-empty string s, s[0] == s[0:1].
There is also no mutable string type, but str.join() or io.StringIO can be used to efficiently construct strings from multiple fragments.
Changed in version 3.3: For backwards compatibility with the Python 2 series, the u prefix is once again permitted on string literals. It has no effect on the meaning of string literals and cannot be combined with the r prefix.
class str(object=’’)
class str(object=b’’, encoding=‘utf-8’, errors=‘strict’)

  • Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is given, as follows.
    If neither encoding nor errors is given, str(object) returns object.str(), which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a str() method, then str() falls back to returning repr(object).
    If at least one of encoding or errors is given, object should be a bytes-like object (e.g. bytes or bytearray). In this case, if object is a bytes (or bytearray) object, then str(bytes, encoding, errors) is equivalent to bytes.decode(encoding, errors). Otherwise, the bytes object underlying the buffer object is obtained before calling bytes.decode(). See Binary Sequence Types — bytes, bytearray, memoryview and Buffer Protocol for information on buffer objects.
    Passing a bytes object to str() without the encoding or errors arguments falls under the first case of returning the informal string representation (see also the -b command-line option to Python). For example:
>>> str(b'Zoot!')
"b'Zoot!'"

3 Chinese content

If you need Chinese content, please click here.

4 Practice

Q: Use four ways to format strings to achieve “521, XXX would you marry me?”(If not entered, the default name is Alice.)

a = input('Please enter a name:')
if a == '':
    a = 'Alice'
print('521,', a, 'would you marry me?')
print('521, ' + a + ' would you marry me?')
print('521, %s would you marry me?'%a)
print(f'521, {a} would you marry me?')
print('521, {} would you marry me?'.format(a))

Q: Now there are three variables: a, b and c. Each of the three variables has a numerical value. Please use the if-else operator to get the maximum of the three values.

import random
try:
    a, b, c = map(int, input('Please enter number a, b, c(Separate with spaces):').split())
except:
    a, b, c = random.randint(0, 100), random.randint(0,100), random.randint(0, 100)
finally:
    print('a: {}, b: {}, c: {}'.format(a, b, c))
    max_ = a if a > b and a > c else b if b > c else c
    print('The largest number is:', max_)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值