Python basic in...login
Python basic introductory tutorial
author:php.cn  update time:2022-04-18 16:14:50

Python string


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

Creating a string is as simple as assigning a value to a variable. For example:

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

Python accesses the value in the string

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

When accessing substrings in Python, you can use square brackets to intercept the string, as shown in the following example:

#!/usr/bin/python

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

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

The above example execution result:

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

Python string update

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

#!/usr/bin/python
# -*- coding: UTF-8 -*-

var1 = 'Hello World!'

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

Execution result of the above example

Update string:- Hello php!

Python escape characters

When special characters need to be used in characters, Python uses backslash (\) to escape characters, as shown in the following table:

##. Escape characterDescription\(at the end of the line)Line continuation character\\Backslash symbol\'Single quote\"Double quotes\aRing\bBackspace##\e\000##\nLine break\vVertical tab character\tHorizontal tab\rEnter\fPage feed\oyy Octal number, the character represented by yy, for example: \o12 represents line feed\xyyHexadecimal number, the character represented by yy, for example: \x0a represents a newline \otherOther characters are output in normal format

Python string operators

The value of instance variable a in the following table is the string "Hello", and the value of variable b is "Python":

Escape
empty
##+String concatenationa + b Output result: HelloPython* Repeated output string a*2 Output result: HelloHello[]Get the characters in the string by indexa[1] Output result[ : ] Intercept part of the stringa[1:4] Output resultinMember Operator - Returns True if the string contains the given character not inMember Operator - Returns True if the string does not contain the given character r/RRaw Strings - Raw Strings: All strings are used literally, without escaping special or unprintable characters. Raw strings have almost the same syntax as ordinary strings, except that the first quotation mark of the string is preceded by the letter "r" (can be uppercase or lowercase). ##%

The example is as follows:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

a = "Hello"
b = "Python"

print "a + b Output result:", a + b
print "a * 2 Output result:", a * 2
print "a[1 ] Output result: ", 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'

The above program is executed The result is:

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 this can lead to very complex expressions, the most basic usage is to insert a value into a string with the string formatting character %s.

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

The following example:

#!/usr/bin/python

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

The above example output result:

My name is Zara and weight is 21 kg!

python string Formatting symbols:


OperatorDescriptionInstance
e
ell
H in a Output result 1
M not in a Output result 1
print r'\n' output\n and print R'\n' output\n
Format stringPlease see the next chapter
## %u Format unsigned integer %o %x %X %f %e## %E %g %G
Symbol Description
%c Format Characters and their ASCII codes
## %s Format string
%d Format integer
## Format unsigned Octal number
Formatted unsigned hexadecimal number
Format unsigned hexadecimal number (uppercase)
Format floating point numbers, you can specify the precision after the decimal point
Use scientific notation to format floating point numbers
Same function %e, format floating point number in scientific notation
Abbreviation for %f and %e
Abbreviations for %f and %E
## %p Use ten Address of hexadecimal format variable
Format operator auxiliary command:

symbol Function*Define width or decimal point precision- Used for left alignment+Display plus sign (+) in front of positive numbers<sp>Display a space before positive numbers##Display zero ('0') before octal numbers, and '0' before hexadecimal numbers 0x' or '0X' (depending on whether 'x' or 'X' is used) 0The displayed number is filled with '0' instead of the default The spaces %'%%' outputs a single '%'(var)Mapping variable (dictionary parameter)##m.n.

Python triple quotes

Triple quotes in python can copy complex strings:

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

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

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

Three quotation marks free programmers from the quagmire of quotation marks and special strings, from beginning to end The format that holds a small piece of string is the so-called WYSIWYG (What You See Is What You Get) format.

A typical use case is when you need a piece of HTML or SQL, then using string combination, special string escaping will be very cumbersome.

errHTML = '''
<HTML><HEAD><TITLE>
Friends CGI Demo</TITLE></HEAD>
<BODY> ;<H3>ERROR</H3>
<B>%s</B><P>
<FORM><INPUT TYPE=button VALUE=Back
ONCLICK="window .history.back()"></FORM>
</BODY></HTML>
'''
cursor.execute('''
CREATE TABLE users (
login VARCHAR(8),
uid INTEGER,
prid INTEGER)
''')

Unicode string

Defining a Unicode string in Python is as simple as defining a normal string:

##>>> u'Hello World !'
u'Hello World ! '
The lowercase "u" before the quotation marks indicates that a Unicode string is created here. If you want to include a special character, you can use Python's Unicode-Escape encoding. As shown in the following example:

>>> u'Hello\u0020World !'
u'Hello World !'

The replaced \u0020 identifier means inserting the Unicode character (space character) with the encoding value 0x0020 at the given position.


Python's built-in string functions

String methods were slowly added from python1.6 to 2.0 - they were also added to Jython.

These methods implement most of the methods of the string module. The following table lists the methods currently supported by the built-in string. All methods include support for Unicode, and some are even specially used. for Unicode.

m is the minimum total width of the display, n is the number of digits after the decimal point (if available)
Check whether the string ends with obj. If beg or end is specified, check whether the specified range ends with obj. If so, return True, otherwise return False.string.expandtabs(tabsize=8)Convert the tab symbols in the string string to spaces, tab The default number of spaces for symbols is 8. ##string.find(str, beg=0, end=len(string))string.index(str, beg=0, end=len(string))string.isalnum()##string.isalpha() Otherwise returns Falsestring.isdecimal() string.isdigit()Use string as the separator to combine all elements (string representations) in seq into a new string string.ljust( width)Returns a new string with the original string left-aligned and padded with spaces to length widthstring.lower()Convert all uppercase characters in string to lowercase.string.lstrip() Truncate the spaces on the left side of string##string.maketrans(intab, outtab])max(str)strmin(str)str##string.partition(str)string.replace(str1, str2, num=string.count(str1))##string.swapcase()Reverse case in stringstring.title()Return "titled" string, that is to say, all words start with uppercase, and the remaining letters are lowercase (see istitle())Convert the characters of string according to the table given by str (containing 256 characters), ##string.upper()string.zfill(width)string.isdecimal()
MethodDescription

string.capitalize()

Capitalize the first character of the string

string.center(width)

Returns a new string with the original string centered and padded with spaces to length width

string.count(str, beg=0, end=len(string))

Returns the number of times str appears in string. If beg or end is specified, the specified number is returned. The number of occurrences of str in the range

##string.decode(encoding='UTF-8', errors='strict')

Decode the string in the encoding format specified by encoding. If an error occurs, a ValueError exception will be reported by default, unless errors specify 'ignore' or 'replace'

string.encode(encoding='UTF-8', errors='strict')

Encode string in the encoding format specified by encoding. If an error occurs, a ValueError exception will be reported by default. Unless errors specify 'ignore' or 'replace'

##string.endswith(obj, beg=0, end=len(string))

Check whether str is included in string. If beg and end specify the range, check whether it is included in the specified range. If it is, return the starting index value, otherwise return -1

The same as the find() method, only However, an exception will be reported if str is not in string.

If string has at least If one character and all characters are letters or numbers,
returns True, otherwise returns False

Returns True if string has at least one character and all characters are letters,

Returns True if string contains only decimal digits, otherwise returns False.

Returns True if string only contains numbers, otherwise returns False.

##string.islower()

If the string contains at least one case-sensitive character, and all these (case-sensitive) characters are lowercase, return True, otherwise return False

string.isnumeric()

If the string contains only numeric characters, return True, otherwise return False

string.isspace()

If the string contains only spaces, it returns True, otherwise it returns False.

string.istitle()

Returns True if string is titled (see title()), otherwise returns False

string.isupper()

If string contains at least one case-sensitive character, and all these (case-sensitive) characters If all are uppercase, return True, otherwise return False

##string.join(seq)

The maketrans() method is used to create a conversion table for character mapping. For the simplest calling method that accepts two parameters, the first parameter is a string representing the characters that need to be converted, and the second parameter Also the target of string representation conversion.

Returns the largest letter in the string
.

Returns the smallest letter in the string
.

A bit like find() and split( ), starting from the first position where str appears, divide the string string into a 3-element tuple (string_pre_str, str, string_post_str). If string does not contain str, string_pre_str == string.

Replace str1 in string with str2. If num is specified, the replacement will not exceed num times.

##string.rfind(str, beg=0,end=len (string) )
Similar to the find() function, but starting from the right.

string. rindex(str, beg=0,end=len(string))
Similar to index(), but starts from the right.

string.rjust(width)
Returns a new string with the original string right-aligned and padded with spaces to length width

string.rpartition(str)
Similar to the partition() function, but starts searching from the right.

string.rstrip()

Remove the spaces at the end of the string string.

##string.split(str="", num=string .count(str))

Use str as the separator to slice string. If num has a specified value, only num substrings will be separated

string.splitlines(num=string.count('\n'))

Separate by row, return a list containing each row as an element , if num is specified, only num rows will be sliced.

string.startswith(obj, beg=0,end=len(string))

Check whether the string starts with obj, if so, return True, otherwise return False. If beg and end specify values, check within the specified range.

string.strip([obj])

Execute lstrip() and rstrip() on string

string.translate(str , del="")

put the characters to be filtered out In the del parameter

Convert the lowercase letters in string to uppercase

Returns a string with a length of width. The original string string is right-aligned and filled in front. 0

The isdecimal() method checks whether a string contains only decimal characters. This method only exists for unicode objects.