Strings of Python Basic Grammar (Part 2)

Author: squid

Recommended column: "Website SEO"

Chasing the wind and chasing the moon don’t stop, the plains are full of spring mountains

 

 

Table of contents

1. Introduction and application of Python string operators

Second, the operation of strings

       1. String indexing and fragmentation

       2, Python connection string

       3, Python modify the string

       4. Other operations

3. Python string formatting

       1. Symbol formatting

       2. Function formatting

       3. Dictionary formatting

Four, Python triple quotes

5. Python's string built-in functions


 

Event address: CSDN 21-day Learning Challenge

1. Introduction and application of Python string operators

The following table instance variable a has the string "Hello" and the b variable has the value "Python":

operator describe example
+ String concatenation a + b output result: HelloPython
* repeat output string a*2 output result: HelloHello
[] Get characters in a string by index a[1] output result e
[ : ] Intercept a part of the string, follow the principle of left closed and right open, str[0:2] does not contain the third character. a[1:4] output result ell
in Member operator - returns True if the string contains the given character H' in a outputs True
not in Member operator - returns True if the string does not contain the given character M' not in a output result True
r/R Raw Strings - Raw Strings: All strings are used literally, without escaping special or unprintable characters. Raw strings have nearly identical syntax to ordinary strings, except that the letter r (which can be upper or lower case) is added before the first quotation mark of the string. print( r'\n' )
print( R'\n' )
% format string  

#!/usr/bin/python3
a = "Hello"
b = "Python"
 
print("a + b 输出结果:", a + b)
print("a * 2 输出结果:", a * 2)
print("a[1] 输出结果:", a[1])
print("a[1:4] 输出结果:", a[1:4])
 
if( "H" in a) :
print("H 在变量 a 中")
else :
 print("H 不在变量 a 中")
 
if( "M" not in a) :
print("M 不在变量 a 中")
else :
print("M 在变量 a 中")
 
print (r'\n')
print (R'\n')

Second, the operation of strings

The following basic operations on strings are included in the Python language:

  • the index of the string
  • slice of string
  • Consolidation of strings
  • repeat string
  • other operations

1. String indexing and fragmentation

    An index, in the Python language, a string is a 有序字符的集合. After a string is created, the relative positions of the characters in it are fixed. The index number of the first character is defined as 0, the index number of the second character is 1, and so on. In the Python language, strings can be forward and reverse indexed. The following table visually represents the correspondence between characters in a string and their index numbers:

The relationship between the characters in the string and the index number
0 1 2 3 4
a b c d and
-5 -4 -3 -2 -1

In the above table, the middle row represents the content of each character in the string, the upper row represents the index number when the string is indexed in the forward direction, and the lower row represents the index number when the string is indexed in reverse.

Indexing is an operation performed on a single element, and the indexing of strings in the Python language is indexed by element subscripts.

>>>s='abcde'
>>>s[1]
"b"
>>>S[3]
"d"
>>>s[4]
"e"

 In the above code, the subscript of the string s is up to 4 (starting from 0).

 Slicing, using the Python language slice (slice) operation, to extract subsequences in a string.

>>>s[1:3]
"bc"
>>>s[1:]
"bcde"
>>>s[-3:-1]
"cd"
>>>s[:-1]
"abcd"
>>>s1=s[:]
"abcd"
>>>s1=s[:]
>>>s1
"abcde"
>>>s[::2]
"ace"
>>>s[::-1]
"edcba"

In the code: s[1:3] gets the substring from 1 to 3 in s; s[1:] gets the element from the index 1 to the end of the string; s[:-1] gets the element from the beginning The element from the beginning to the end of the string. The subscript of s[::2] starts from 0, and takes one element every other character; s[::-1] implements the reverse order operation on the string.

2, Python connection string

String concatenation is the concatenation of two or more strings into one string. When concatenating strings, the Python language allocates memory for each concatenated string and the newly generated string, increasing unnecessary memory overhead.

(1) Operator ("+") method:

>>>'py'+'th'+'on'
'python'
>>>'python'+'is'+''+'easy'
'python is easy'

(2) The Python language uses the string formatting operator (%) and the join() method to connect strings in two ways

operator (%) method

>>>'%s%s%s'%('py','th','on')
'python'
>>>'%s%s%s'%('python','is','easy')
'python is easy'

join() method

>>>".join(('py','th','on'))
'python'
>>>''.join(('python','is','easy'))
'python is easy'

3, Python modify the string

In the Python language, strings are immutable types, and characters in the original string cannot be modified or deleted.

Connection by plus sign

>>>s='python
>>>s+'cool'
'pythoncool'

By slicing the original string and then concatenating

>>>s='python'
>>>'C'+s[1:]
'Cython'

replace() function to modify the string

>>>s='python'
>>>s.replace('p','C')
'Cython'

The function of the replace() function is character replacement. If the source character or string to be replaced exists and is different from the target character or string to be replaced, the return value is a recreated string object; otherwise, the original character is returned String object. The code uses the replace() function to replace the 'p' in the string s with 'C'.

4. Other operations

Use the helper functions to view the operation methods of string objects. These methods can be called by means of object.attribute.

3. Python string formatting

String formatting is to control the output form of the string so that it is output in the way the developer expects. There are three main ways to format strings:

  • Symbol formatting
  • function formatting
  • dictionary formatting

1. Symbol formatting

Symbol formatting mainly uses "%+formatting symbols" and the corresponding formatting auxiliary symbols to format strings.

symbol describe
 %c Format characters and their ASCII codes
%s format string
%d format integer
%in format unsigned int
%O format unsigned octal number
%x format unsigned hexadecimal number
%X format an unsigned hexadecimal number (uppercase
%f Format a floating point number, specifying the precision after the decimal point
%and Format floating point numbers in scientific notation
%AND Same as %e, format floating point numbers in scientific notation
%g Shorthand for %f and %e
%G Shorthand for %f and %E
%p Format the address of a variable with a hexadecimal number

Formatting operator helper:

symbol Function
* define width or decimal point precision
- used for left alignment
+ Display a plus sign ( + ) in front of positive numbers
<sp> Display spaces before positive numbers
# Displays zero ('0') in front of octal numbers and '0x' or '0X' in front of hexadecimal numbers (depending on whether 'x' or 'X' is used)
0 The displayed numbers are padded with '0' instead of the default space
% '%%' outputs a single '%'
(was) map variable (dictionary parameter)
m.n. m is the minimum overall width of the display, n is the number of digits after the decimal point (if available)

2. Function formatting

Python 支持格式化字符串的输出 。尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中。在 Python 中,字符串格式化使用与 C 中 sprintf 函数一样的语法。

#!/usr/bin/python3
 
print ("我叫 %s 今年 %d 岁!" % ('小明', 10))

以上实例输出结果:

我叫 小明 今年 10 岁!

3、字典格式化

在Python语言中,字典格式化是在左边的格式化字符串通过引用右边字典中的键来提取对应的值,实现格式化输出。

四、Python三引号

python三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符。实例如下:

#!/usr/bin/python3
 
para_str = """这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( \t )。
也可以使用换行符 [ \n ]。
"""
print (para_str)

以上实例执行结果为:

这是一个多行字符串的实例
多行字符串可以使用制表符
TAB (    )。
也可以使用换行符 [ 
 ]。

 五、Python 的字符串内建函数

Python 的字符串常用内建函数如下:

序号 方法及描述
1 capitalize()
将字符串的第一个字符转换为大写
2 center(width, fillchar)
返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。
3 count(str, beg= 0,end=len(string))
返回 str string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数
4 bytes.decode(encoding="utf-8", errors="strict")
Python3 中没有 decode 方法,但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象,这个 bytes 对象可以由 str.encode() 来编码返回。
5 encode(encoding='UTF-8',errors='strict')
以 encoding 指定的编码格式编码字符串,如果出错默认报一个ValueError 的异常,除非 errors 指定的是'ignore'或者'replace'
6 endswith(suffix, beg=0, end=len(string))
检查字符串是否以 obj 结束,如果beg 或者 end 指定则检查指定的范围内是否以 obj 结束,如果是,返回 True,否则返回 False.
7 expandtabs(tabsize=8)
把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8 。
8 find(str, beg=0, end=len(string))
检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则返回-1
9 index(str, beg=0, end=len(string))
跟find()方法一样,只不过如果str不在字符串中会报一个异常。
10 isalnum()
如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False
11 isalpha()
如果字符串至少有一个字符并且所有字符都是字母或中文字则返回 True, 否则返回 False
12 isdigit()
如果字符串只包含数字则返回 True 否则返回 False..
13 islower()
如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
14 isnumeric()
如果字符串中只包含数字字符,则返回 True,否则返回 False
15 isspace()
如果字符串中只包含空白,则返回 True,否则返回 False.
16 istitle()
如果字符串是标题化的(见 title())则返回 True,否则返回 False
17 isupper()
如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False
18 join(seq)
以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串
19 len(string)
返回字符串长度
20 ljust(width[, fillchar])
返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。
21 lower()
转换字符串中所有大写字符为小写.
22 lstrip()
截掉字符串左边的空格或指定字符。
23 maketrans()
创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
24 max(str)
返回字符串 str 中最大的字母。
25 min(str)
返回字符串 str 中最小的字母。
26 replace(old, new [, max])
把 将字符串中的 old 替换成 new,如果 max 指定,则替换不超过 max 次。
27 rfind(str, beg=0,end=len(string))
类似于 find()函数,不过是从右边开始查找.
28 rindex( str, beg=0, end=len(string))
类似于 index(),不过是从右边开始.
29 rjust(width,[, fillchar])
返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串
30 rstrip()
删除字符串末尾的空格或指定字符。
31 split(str="", num=string.count(str))
以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num+1 个子字符串
32 splitlines([keepends])
Separated by lines ('\r', '\r\n', \n'), returns a list containing each line as an element. If the parameter keepends is False, no newlines are included, if True, newlines are preserved.
33 startswith(substr, beg=0,end=len(string))
Checks if the string starts with the specified substring substr, returns True if it is, otherwise returns False. If beg and end specify values, check within the specified range.
34 strip([chars])
perform lstrip() and rstrip() on strings
35 swapcase()
Convert uppercase to lowercase and lowercase to uppercase in a string
36 title()
Returns a "titled" string, that is, all words start with uppercase and the rest are lowercase (see istitle())
37 translate(table, deletechars="")
Convert the characters of string according to the table given by table (contains 256 characters), and put the characters to be filtered out into the deletechars parameter
38 upper()
Convert lowercase letters in a string to uppercase
39 zfill (width)
Returns a string of length width, the original string is right-aligned, and the front is filled with 0
40 isdecimal()
Checks if the string contains only decimal characters, returns true if so, false otherwise.

Guess you like

Origin blog.csdn.net/m0_71172453/article/details/126254571