Python Base 4-string

Source: Internet
Author: User
Tags printable characters

The content of this section:

1. Create a string

2. accessing values in a string

3. escape characters in a string

4. String Operators

5. string Formatting

6. built-in functions for strings

1. Create a string

var1 = ' Hello world! ' VAR2 = "Chen71"

2. Accessing values in a string

Python to access substrings, you can use square brackets to intercept strings

var1 = ' Hello world! ' VAR2 = "Chen71" Print ("var1[0]:", var1[0])     #截取第一个字符print ("Var2[1:5]:", Var2[1:5]) #截取第2-A-character

  

3. Escape characters in a string

Python uses a backslash (\) to escape characters when special characters are needed in a string. As the following table:

Escape Character Description
\ (at end of line) Line continuation character
\\ Backslash symbol
\‘ Single quotation marks
\" Double quotes
\a Bell
\b BACKSPACE (Backspace)
\e Escape
\000 Empty
\ n Line break
\v Portrait tab
\ t Horizontal tab
\ r Enter
\f Page change
\oyy Octal number, the character represented by YY, for example: \o12 for newline
\xyy Hexadecimal number, the character represented by YY, for example: \x0a for line break
\other Other characters are output in normal format

4. String operators

The following table instance variable a value is the string "Hello" and the B variable value is "Python":

operator Description Example
+ String connection A + B output result: Hellopython
* Repeating output string A*2 Output Result: Hellohello
[] Getting characters in a string by index A[1] Output result e
[ : ] Intercept part of a string A[1:4] Output results ell
Inch Member operator-Returns TRUE if the string contains the given character ' H ' in a output result 1
Not in Member operator-Returns TRUE if the string does not contain the given character ' M ' not in a output result 1
R/r Raw string-Raw string: all strings are used directly as literal meanings, without escaping special or non-printable characters. The original string has almost exactly the same syntax as a normal string, except that the first quotation mark of the string is preceded by the letter R (which can be case).
Print( r' \ n ')print(' r\n ')       
% format string

5. String formatting

% formatting

Print ("My name%s is%d years old!"% (' Xiao Ming ', 10))

Python string formatting symbols:

symbols Description
%c Formatting characters and their ASCII code
%s formatting strings
%d formatting integers
%u Formatting an unsigned integer
%o Formatting an unsigned octal number
%x formatting unsigned hexadecimal numbers
%x Format unsigned hexadecimal number (uppercase)
%f Format floating-point numbers to specify the precision after a decimal point
%e Format floating-point numbers with scientific notation
%E function with%e, format floating-point numbers with scientific notation
%g Shorthand for%f and%e
%G Shorthand for%f and%E
%p Format the address of a variable with hexadecimal number

Formatting operator Auxiliary directives:

symbols function
* Define width or decimal precision
- Used for left justification
+ Used for right justification
<sp> Show spaces in front of positive numbers
# Displays 0 (' 0 ') before the octal number, preceded by ' 0x ' or ' 0X ' in hexadecimal (depending on ' x ' or ' x ')
0 The displayed number is preceded by ' 0 ' instead of the default space
% ' percent ' output a single '% '
(VAR) mapping variables (dictionary parameters)
M.N. M is the minimum total width displayed, and n is the number of digits after the decimal point (if available)

  

The format can be further controlled in the following ways:

%[(name)][flags][width]. [Precision]typecode

(name) is named

Flags can have +,-, ' or 0. + Indicates right alignment. -Indicates left alignment. ' is a space that fills a space on the left side of a positive number to align with a negative number. 0 means using 0 padding.

Width indicates display widths

Precision indicates the precision after the decimal point

#定义宽度或者小数精度print ("%.*f"% (4, 1.2)) is equivalent to print ("%.4f"% (1.2)) #用作左对齐print ("%-10s"% ("Hello")) #0填充print ("%04d"% 5) #映射变量, followed by dictionary parameter print ("Hello% (name), you is% (weight) kg"%{' name ': ' chen71 ', ' Weight ': 60})

 

Built-in functions formatted with format ()

Support for Str.format () format function after Python2.6

The basic use of the format () function is demonstrated directly through a simple example:

# Positional parameter print ("{0} is {1} years-old". Format ("Chen71", +)) print ("{} is {} years-old". Format ("Chen71", +) print ("Hi, {0}!  {0} is {1} years old ". Format (" Chen71 ", 100)) # keyword parameter print (" {name} is {age} years old ". Format (name =" Chen71 ", age = 100) # Subscript parameter Li = ["Chen71", 100]print ("{0[0]} is {0[1]} years old". Format (LI)) # Fill and align # ^, <, > center, Align Left, right, followed by width #: number with fill after character, which is not specified, the default is to fill print with a space (' {: >8} ') print (' {: <8} '. Format (' 3.14 ')) print (' {: ^8} '. Format (' 3.14 ') print (' {: 0>8} '. Format (' 3.14 ')) print (' {: a>8} '. Format (' 3.14 ')) # floating-point Precision print (' {:. 4f} '. Format (3.1415926 ) Print (' {: 0>10.4f} '. Format (3.1415926)) # binary # B, D, O, and X are binary, decimal, octal, hexadecimal print (' {: b} '. Format (one)) print (' {:d} '). Format (one)) print (' {: o} '. Format (one)) print (' {: x} '. Format ()) print (' {: #x} '. Format (one)) print (' {: #X} '. Format (11)) # Thousands separator print (' {:,} '. Format (15700000000))

6. Built-in functions for strings

Python's string commonly built-in functions are as follows:

Serial Number Method and Description
1

Capitalize ()
Converts the first character of a string to uppercase

2

Center (width, Fillchar)


Returns a string that specifies the width of the center, Fillchar is a filled character, and the default is a space.
3

Count (str, beg= 0,end=len (String))


Returns the number of occurrences of STR in a string, if beg or end specifies that the number of STR occurrences in the specified range is returned
4

Bytes.decode (encoding= "Utf-8", errors= "strict")


There is no Decode method in Python3, but we can use the decode () method of the Bytes object to decode the given bytes object, which can be encoded back by bytes ().
5

Encode (encoding= ' UTF-8 ', errors= ' strict ')


Encodes a string in the encoded format specified by encoding, if an error defaults to a ValueError exception unless errors specifies ' ignore ' or ' replace '
6

EndsWith (suffix, beg=0, End=len (String))
Checks whether the string ends with obj, or returns False if beg or end specifies whether to end with obj in the specified range, or True if it is.

7

Expandtabs (tabsize=8)


Turns the tab symbol in string strings to a space, and the default number of spaces for the tab symbol is 8.
8

Find (str, beg=0 End=len (String))


Detects if STR is contained in a string, and if the range beg and end is specified, the check is contained within the specified range and returns 1 if it contains the index value that returns the start.
9

Index (str, beg=0, End=len (String))


Just like the Find () method, only if STR does not report an exception in the string.
10

Isalnum ()


Returns True if the string has at least one character and all characters are letters or numbers, otherwise False
11

Isalpha ()


Returns True if the string has at least one character and all characters are letters, otherwise False
12

IsDigit ()


Returns True if the string contains only a number, otherwise False:
13

Islower ()


Returns True if the string contains at least one case-sensitive character, and all of these (case-sensitive) characters are lowercase, otherwise False
14

IsNumeric ()


Returns True if the string contains only numeric characters, otherwise False
15

Isspace ()


Returns True if the string contains only white space, otherwise False.
16

Istitle ()


Returns True if the string is heading (see Title ()), otherwise False
17

Isupper ()


Returns True if the string contains at least one case-sensitive character, and all of these (case-sensitive) characters are uppercase, otherwise False
18

Join (SEQ)


Merges all elements of the SEQ (the string representation) into a new string with the specified string as a delimiter
19

Len (String)


return string length
20

Ljust (width[, Fillchar])


Returns a string that is left-justified by using Fillchar to fill a new string of length width, and fillchar the default is a space.
21st

Lower ()


Converts all uppercase characters in a string to lowercase.
22

Lstrip ()


Truncates the left space of the string or specifies the character.
23

Maketrans ()


To create a conversion table of character mappings, for the simplest invocation of two parameters, the first argument is a string representing the character that needs to be converted, and the second argument is the target of the string representation of the transformation.
24

Max (str)


Returns the largest letter in the string str.
25

Min (str)


Returns the smallest letter in the string str.
26

Replace (old, new [, Max])


Replace the str1 in the string with str2, and if Max specifies it, the replacement does not exceed Max times.
27

RFind (str, Beg=0,end=len (String))


Similar to the Find () function, it is just looking from the right.
28

Rindex (str, beg=0, End=len (String))


Similar to index (), but starting from the right.
29

Rjust (width,[, Fillchar])


Returns the right alignment of an original string and fills a new string of length width with Fillchar (default space)
30

Rstrip ()


Removes a space at the end of a string string.
31

Split (str= "", Num=string.count (str))


Num=string.count (str)) intercepts a string with the Str delimiter, and only the NUM substring if NUM has a specified value
32

Splitlines ([keepends])


Separated by rows (' \ r ', ' \ r \ n ', \ n '), returns a list containing the rows as elements, if the argument keepends is False, does not contain a newline character, and if true, the newline character is preserved.
33

StartsWith (str, Beg=0,end=len (String))


Checks whether the string starts with obj, returns True, or False. If beg and end specify a value, the check is within the specified range.
34

Strip ([chars])


Execute Lstrip () and Rstrip () on a string
35

Swapcase ()


Convert uppercase in a string to lowercase, lowercase to uppercase
36

Title ()


Returns the "heading" string, meaning all words start with uppercase and the remaining letters are lowercase (see istitle ())
37

Translate (table, deletechars= "")


Converts a string character to a table (containing 256 characters) given by STR, and the character to be filtered out into the Deletechars parameter
38

Upper ()


lowercase letters in a converted string are capitalized
39

Zfill (width)


Returns a string of length width, the original string right-aligned, front padding 0
40

Isdecimal ()


Checks whether the string contains only decimal characters and returns False if true.

Reference Link: http://www.runoob.com/python3/python3-string.html

Reference Link: https://www.cnblogs.com/wilber2013/p/4641616.html

Python Base 4-string

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.