A string is an ordered collection of characters that can be used to obtain a specific element by its location. In Python, the characters in a string are extracted by an index, starting at 0.
Python can take a negative value, which means it is extracted from the end, the last is-1, and the penultimate is-2, which is what the program thinks can be reversed at the end.
>>> s1="Hello">>> s2="Hello World">>> S1inchs2true>>> WinchS2traceback (most recent): File"<pyshell#3>", Line 1,inch<module>WinchS2nameerror:name'W' is notdefined>>>"W" inchs2true>>>"W" inchS1false>>> s1==S2false>>>ifS1! = S2:Print('No') No>>>S2'Hello World'>>>S1'Hello'>>>Print(s2[0]) H>>>Print(s2[-1]) d>>>Print(S2[0:5]) Hello>>>Print(S2[0:4]) Hell>>>Print(S2[:5]) Hello>>>Print(s2[6:]) World>>>Print(s2[-5]) W>>>Print(s2[-5:]) World>>>Print([S2]) ['Hello World']>>>Print(s2[:]) Hello world>>>Print(S2[::2]) HLOWRD>>>Print(S2[1:7:2]) El
formatting strings
When formatting a string, Python uses a string as a template. There are formatting characters in the template that reserve locations for real values and describe the format in which real values should be rendered. Python uses a tuple to pass multiple values to the template, each of which corresponds to a format character.
For example, the following:
Print ("I ' m%s.") I ' m%d year old"% ('vamei',") ")
In the example above,
"I ' m%s. I ' m%d year old " for our template.
%s is the first format character, which represents a string. %d is the second format character, which represents an integer.
(' Vamei ', 99) Two elements ' Vamei ' and 99 are substituted for the true values of%s and%d.
Between the template and the tuple, there is a % number separated, which represents the format operation.
The entire "I ' m%s. I ' m%d year old "% (' Vamei '," a ") actually forms a string expression.
We can assign a value to a variable as if it were a normal string. For example:
"I ' m%s. I ' m%d year old"% ('vamei')print (a)
Or a ('vamei')
We can also use dictionaries to pass real values. As follows:
Print ("I ' m% (name) s. I ' m% (age) D-year-old"% {'name':'vamei' age': ()})
As you can see, we have named two of the format characters . The name is used () enclosed. A key for each named corresponding dictionary.
format character
The format character reserves the location for the real value and controls the format of the display. A format character can contain a type code that controls the type of display, as follows:
%s string (shown with STR ())
%r string (shown with repr ())
%c single character
%b binary integers
%d decimal integers
%i Decimal Integer
%o Eight-binary integers
%x hexadecimal integer
%e index (base written as E)
%E index (base written as E)
%f floating Point
%F floating-point number, same as above
%g index (e) or floating point number (depending on display length)
%G Index (E) or floating point number (depending on display length)
Percent% character "%"
Python String Shard Index