Latest web development tutorials

Python3 string

Python strings are the most commonly used data types. We can use quotation marks ( 'or ") to create a string.

Create a string is very simple, as long as the variable is assigned a value. E.g:

var1 = 'Hello World!'
var2 = "w3big"

Python access string value

Python does not support single character type, a single character is also used as a Python strings.

Python access substring, you can use square brackets to intercept string following examples:


var1 = 'Hello World!'
var2 = "w3big"

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

The results of the above examples:

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

Python string Update

You can modify an existing string, and assign them to another variable, the following examples:


var1 = 'Hello World!'

print ("已更新字符串 : ", var1[:6] + 'w3big!')

Examples of the results of the above

已更新字符串 :  Hello w3big!

Python escape character

When you need to use special characters in the character, python with a backslash (\) escape character. In the following table:

Escape character description
\ (At the end of the line) ULink
\\ Backslash
\ ' apostrophe
\ " Double quotes
\ A Bell
\ B Backspace (Backspace)
\ E Escape
\ 000 air
\ N Wrap
\ V Vertical tab
\ T Horizontal tab
\ R Enter
\ Oyy Character octal, yy representatives, for example: \ o12 represent the newline
\ Xyy Character hexadecimal number, yy representatives, for example: \ x0a represent the newline
\ Other Other character output in a common format

Python string operators

The following table instance variable is a string "Hello", b variable value "Python":

Operators description Examples
+ String concatenation a + b output: HelloPython
* Repeat output string a * 2 output: HelloHello
[] Gets characters in the string by index a [1] outpute
[:] Interception of the string part a [1: 4] outputell
in Member operator - If the string contains the given character returns True H in a 1 output
not in Member operator - If the string does not contain a given character returns True M not in a 1 output
r / R The original string - the original string: all strings are directly used in accordance with the literal meaning, there is no escaping special characters or not print. In addition to the original string before the first quote with the letter "r" (may be the case) than with ordinary string has an almost identical syntax. print r '\ n' prints \ n and print R '\ n' prints \n
% Format string See the next section.



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')

The above example output is:

a + b 输出结果: HelloPython
a * 2 输出结果: HelloHello
a[1] 输出结果: e
a[1:4] 输出结果: ell
H 在变量 a 中
M 不在变量 a 中

Python string formatting

Python supports output formatted strings. Although this can include very complicated expressions, the most basic usage is to insert a value into a string string specifier% s in.

In Python, and C string formatted using the same syntax as the sprintf function.

The following examples:


print ("我叫 %s 今年 %d 岁!" % ('小明', 10))

Examples of the above output:

我叫 小明 今年 10 岁!

python string formatting symbols:

Symbol description
% c Formatting characters and their ASCII code
% s Format string
% d Integer format
% u Unsigned int format
% o Formatting unsigned octal
% x Unsigned hexadecimal format
% X Unsigned hexadecimal format (uppercase)
% f Format floating-point numbers, the accuracy can be specified after the decimal point
% e Scientific notation floating point format
% E Action with% e, using scientific notation floating point format
% g % f and% e shorthand
% G % f% E and shorthand
% p Hexadecimal address format number of variables

Formatting operator assisted instruction:

symbol Features
* Define the width or decimal precision
- Alignment of the left do
+ Positive numbers displayed on the front plus sign (+)
<Sp> Display space before positive numbers
# Show zero in front of the octal number ( '0'), in front of the hexadecimal display '0x' or '0X' (depending on the use the 'x' or 'X')
0 The figures show the front fill '0' instead of the default spaces
% '%%' Outputs a single '%'
(Var) Variable mapping (dictionary parameter)
mn m is the minimum overall width of the display, n is the number of decimal places (if available)

Python triple quotes

python triple quotes allow a string across multiple lines, the string can contain line breaks, tabs, and other special characters. Examples are as follows


para_str = """这是一个多行字符串的实例
TAB ( \t )。
也可以使用换行符 [ \n ]。
print (para_str)

The above examples Implementation of the results:

TAB (    )。
也可以使用换行符 [ 

Triple quotes allow programmers from the quagmire inside quotes and special strings start to finish to maintain a small format string is called WYSIWYG (WYSIWYG) format.

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

errHTML = '''
Friends CGI Demo</TITLE></HEAD>
CREATE TABLE users (  
login VARCHAR(8), 

Unicode strings

In Python2, the normal 8-bit ASCII code strings are stored, and the Unicode strings are stored as 16-bit unicode string, this can represent more character sets. The syntax used in the string preceded by the prefixu.

In Python3, all strings are Unicode strings.

Python string built-in functions

Python string commonly used built-in functions as follows:

No. Method and Description

capitalize ()
The first character of the string to uppercase


center (width, fillchar)

Returns a specified width width centered string, fillchar to fill characters, the default is spaces.

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

Returns the number of times the string str appears inside, str occur if the beg or end specified is returned within the specified range

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

To decode encoded using the specified string. The default encoding is a string encoding.

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

In encoding the specified encoding format string, the default error message if a ValueError exception, unless the errors specified is 'ignore' or 'replace'

endswith (suffix, beg = 0, end = len (string))
Check whether the string obj end, if specified beg or end within the specified range is checked whether obj end, and if so, returns True, otherwise False.


expandtabs (tabsize = 8)

String string in tab symbol into space, tab symbols for the default number of spaces is 8.

find (str, beg = 0 end = len (string))

Detection is included in the string str, if you beg and end the specified range, it is checked whether contained within the specified range, if it is the beginning of the index value is returned, otherwise -1

index (str, beg = 0, end = len (string))

With the find () method of the same, but if the string str is not an exception will be reported.

isalnum ()

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

isalpha ()

If there is at least one character string and all the characters are letters it returns True, otherwise False

isdigit ()

If the string contains only numeric Returns True otherwise return False ..

islower ()

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

isnumeric ()

If the string contains only numeric characters, it returns True, otherwise False

isspace ()

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

istitle ()

If the string is the title (see title ()) returns True, otherwise False

isupper ()

If the string contains at least one of alphanumeric characters, and all of these (case-sensitive) characters are uppercase, it returns True, otherwise False

join (seq)

In the specified string as a delimiter, will seq all elements (string representation) into a new string

len (string)

Returns the string length

ljust (width [, fillchar])

Returns a string of former left-justified, and use fillchar filled to the new string of length width, fillchar default spaces.
twenty one

lower ()

Convert a string to all uppercase characters to lowercase.
twenty two

lstrip ()

Truncated string left spaces
twenty three

maketrans ()

Character Map to create a conversion table for the two arguments simplest invocation, the first argument is a string that represents the character to be converted, the second parameter is the string representation of goal conversions.
twenty four

max (str)

Returns the string str largest letters.

min (str)

Returns the string str smallest letters.

replace (old, new [, max ])

The replaces the string str1 into str2, if max specified, replace no more than max times.

rfind (str, beg = 0, end = len (string))

Similar to the find () function, but start looking from the right.

rindex (str, beg = 0, end = len (string))

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

rjust (width, [, fillchar] )

Returns a string of former right-aligned, and use fillchar (default blank) is filled to the length of the width of the new string

rstrip ()

Remove string of spaces at the end of the string.

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

num = string.count (str)) to str-delimited string interception, if num value is specified, then only substrings interception num

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

Separated by rows, each row is returned as an element of a list that contains only the sections specified if num num rows.

startswith (str, beg = 0, end = len (string))

Check whether a string begins with obj, it returns True, otherwise False. If beg and end the specified value, check within the specified range.

strip ([chars])

Executive lstrip to the string () and rstrip ()

swapcase ()

String uppercase to lowercase and lowercase to uppercase

title ()

Back "title" of the string, that are all words beginning with a capital, and the remaining letters are lowercase (see istitle ())

translate (table, deletechars = "" )

Table str given (256 characters) to convert the character string to filter out the character argument put deletechars

upper ()

Conversion string lowercase to uppercase

zfill (width)

Returns a string of length width, the original string right justified, padded with zeros in front

isdecimal ()

Check whether the string contains only the decimal character, if it returns true, otherwise returns false.