Python Basic Tutorial Notes 11: Strings

Strings are the most commonly used data type in Python. We can use quotes (' or ") to create strings.

Creating strings is as simple as assigning a value to a variable. E.g:

var1 = 'Hello World!'
var2 = "Python Runoob"

Python access value in string

Python does not support single-character types , and single-characters are also used as a string in Python.

To access substrings in Python, you can use square brackets to intercept strings, as in the following example:

var1 = 'Hello World!'
var2 = "Python Runoob"

print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]

result:

var1 [0 ]: H
var2 [ 1: 5]: ytho

Python string update

You can modify an existing string and assign it to another variable, as in the following example:

var1 = 'Hello World!'

print "Update string:- ", var1[:6] + 'Runoob!'

result:

Update String:- Hello Runoob!

Python escape character

Python escapes the character with a backslash (\) when special characters are required within a character . The following table:

\(at the end of the line) #continuation character
\\ # backslash symbol
\ ' #single quote
\" #Double quotes
\a #bell
\b #Backspace
\e #escape
\ 000              #null
\n #newline
\v #vertical tab character
\t #horizontal tab
\r #Enter
\f # form feed
\oyy #octal number, the character represented by yy, for example: \o12 represents newline
\xyy #hexadecimal number, the character represented by yy, for example: \x0a represents newline
\other #Other characters are output in normal format

Python string operators

The value of the instance variable a in the following table is the string "Hello", and the value of the b variable is "Python" + string concatenation        >>>a + b                 'HelloPython'

*     Repeat the output string        >>>a * 2 
                'HelloHello' [] Get the characters in the string by index >>>a[1]                   'e' [ : ] truncate part of string >>>a[1:4]
                  'ell'
in member operator - returns True if the string contains the given character   >>>"H" in a
                                 True not in member operator
- returns True if the string does not contain the given character >>>"M" not in a                                   True r /R Raw Strings - Raw Strings: All strings are used literally, without escaping special or unprintable characters. Raw strings have nearly the same syntax as normal strings, except that                                  the letter "r" (which can be upper or lower case) is added before the first quotation mark of the>>>print r'\n'
                                \n
                                >>> print R'\n'    

                                \n
% format string

Examples are as follows:

a = "Hello"
b = "Python"

print "a + b output result: ", a + b
print "a * 2 output: ", a * 2  
print "a[1] output: ", a[1 ]
print "a[1:4] output result: ", a[1:4 ]

if( "H" in a) :
    print "H is in variable a" 
 else :
    print "H is not in variable a"

if( "M" not in a) :
    print "M is not in variable a" 
 else :
    print "M is in variable a"

print r'\n'
print R'\n'

result:

a + b output result: HelloPython
a *2 output result: HelloHello
a[ 1 ] output result: e
a[ 1:4 ] output result: ell
H is in variable a
M is not in variable a
\n
\n

Python string formatting

Python supports formatted string output. Although very complex expressions can be used, the most basic usage is to insert a value into a string with the string formatter %s.

In Python, string formatting uses the same syntax as the sprintf function in C.

Python string formatting symbols :

    Symbol description
       % c Format character and its ASCII code
       % s Format string
       % d Format integer
       % u Format unsigned integer
       % o Format unsigned octal number
       % x Format unsigned hexadecimal number
       % X Format unsigned hexadecimal numbers (uppercase)
       % f Format floating point numbers, you can specify the precision after the decimal point
       % e Format floating point numbers in scientific notation
       %E Same as % e, format in scientific notation Shorthand for floating point numbers
       %g %f and % e
       %G Shorthand for %f and % E
       %p Format the address of a variable in hexadecimal

Formatting operator helper:

Symbolic functions
 *      define width or decimal precision
 -     used for left justification
 + display plus sign ( + )
 in front of positive numbers <sp>     display space in front of positive numbers# Display zeros ( '0') in 
front of octal numbers , '0x' or '0X' (depending on whether 'x' or 'X' is used) in hexadecimal numbers )
 0 Display numbers preceded by '0' instead of the default whitespace
 % '%%' outputs a single '%'
(var) map variable (dictionary parameter)
mn m is the minimum total width of the display, n is the number of digits after the decimal point (if available)

 

The following example:

print "My name is %s and weight is %d kg!" % ('Zara', 21) 

result:

My name is Zara and weight is 21 kg!

Python triple quotes

Triple quotes in python can copy complex strings:

Python triple quotes allow a string to span multiple lines, and the string can contain newlines, tabs, and other special characters.

The syntax of triple quotes is a pair of consecutive single or double quotes (usually used in pairs).

>>> hi = '''hi
there'''
>>> hi   # repr()
'hi\nthere'
>>> print hi  # str()
hi
there  

Triple quotation marks free the programmer from the quagmire of quotation marks and special strings, and keep a small piece of string in the so-called WYSIWYG (what you see is what you get) format from beginning to end.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324661624&siteId=291194637