Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python string


May 10, 2021 Python2


Table of contents


Python string

Strings are the most commonly used data types in Python. We can use quotation marks to create strings.

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

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

Python accesses the value in the string

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

Python accesses substrings, which can be intercepted using square brackets, as follows:

#!/usr/bin/python

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

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

The results of the above example execution:

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

Python string update

You can modify an existing string and assign it to another variable, as follows:

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

var1 = 'Hello World!'

print "更新字符串 :- ", var1[:6] + 'w3cschool!'

The above instance executes the results

更新字符串 :-  Hello w3cschool!


Python escape character

When you need to use special characters in characters, Python escapes characters with a backslash. Here's the table:

Escape characters Describe
(at the end of the line) The line break
\\ Backslash symbol
\' Single quotes
\" Double quotes
\a Bell
\b Backspace
\e Escape
00 Empty
\n Line change
\v Vertical tabs
\t Landscape tabs
\r Enter
\f Change the page
\oyy Octal number, yy for the character, e.g.: so12 for line changes
\xyy Hex, yy for characters, e.g.: sx0a for line changes
\other Other characters are output in normal format

Python string operator

The following table example variable a value is the string "Hello" and the b variable value is "Python":

Operator Describe Instance
+ String connection A-b Output: HelloPython
* Repeat the output string a :2 Output: Hello Hello
[] Get the characters in the string through the index The output e
[ : ] Intercept a portion of the string a s1:4 s output ell
in Member Operator - True if the string contains a given character H in a output 1
not in Member Operator - True if the string does not contain a given character M not in a output 1
r/R Original String - Original String: All strings are used literally, with no escaped special or unprintable characters. The original string has an almost identical syntax to a normal string, except that it has the letter "r" (caseable) before the first quotation mark of the string. print r'n' prints'n and print R'n'prints'
% The format string Let's take a look at the next section

Here's an example:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

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 procedures are performed as follows:

a + b 输出结果: HelloPython

a * 2 输出结果: HelloHello

a[1] 输出结果: e

a[1:4] 输出结果: ell

H 在变量 a 中

M 不在变量 a 中

\n

\n


Python string formatting

Python supports formatting the output of strings. Although this may use very complex expressions, the most basic use is to insert a value into a string with the string format %s.

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

Here's an example:

#!/usr/bin/python

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

The above example output results:

My name is Zara and weight is 21 kg!

Python string formatting symbol:

the number of the character Describe
%c Format characters and their ASCII codes
%s Format the string
%d Format the integer
%u Format unsigned integers
%o Format the unsigned octal number
%x Format the unsigned hete sixteenths
%X Format unsigned heteens (capital)
%f Format floating-point numbers to specify the accuracy after the scale
%e Format floats with scientific notation
%E Acting like %e, floating points are formatted by scientific notation
%g A short history of %f and %e
%G Short case of %f and %E
%p Format the address of the variable in hete sixteenths

Format operator auxiliary instructions:

Symbol Function
* Define width or scale accuracy
- Use to make left alignment
+ Show the plus sign in front of the positive number ( . . .
<sp> Spaces are displayed before the positive number
# Show zero ('0') in front of octals, '0x' or '0X' in front of hex (depending on whether 'x' or 'X' is used)
0 The displayed number is filled with '0' instead of the default space
% '%%' outputs a single '%'
(var) Map variables (dictionary parameters)
m.n. m is the minimum total width displayed, n is the number of digits after the scale (if available)

Python three quotes (triple quotes)

Three quotation marks in Python can copy complex strings:

Python three quotation marks allow a string to span multiple lines, and a string can contain line breaks, tabs, and other special characters.

The syntax of three quotation marks is a pair of consecutive single or double quotation marks (usually in pairs).

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

The three quotation marks free the programmer from the quagmire of quotation marks and special strings, keeping a small string in the format of the so-called WYSIWYG (WYSIWYG) format from start to finish.

A typical use case is when you need an HTML or SQL, and with string combinations, special string escapes can be 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 !'

A "u" in pre-quotes indicates that a Unicode string is created here. I f you want to add a special character, you can use Python's Unicode-Escape encoding. Here's an example:

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

The replaced .u0020 identity represents the insertion of a Unicode character (space character) with an encoded value of 0x0020 at a given location.


Python's string built-in function

String methods are slowly added from Python 1.6 to 2.0 -- they are also added to Jython.

These methods implement most of the methods of the string module, and list the methods currently supported by string built-in as shown in the following table, all of which include support for Unicode, some even specifically for Unicode.

Method Describe

string.capitalize()

Capital the first character of the string

string.center(width)

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

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

Returns the number of times str appears in the string, and returns the number of str appearances within the specified range if the beg or end specifies

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

Decode the string in the encoding format specified by encoding, and if an error is reported by default to a ValueError anomaly, except that non-errors refer to 'ignore' or 'replace'

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

Encode string in encoding-specified format, if an error is reported by default to a ValueError exception, unless the errors specify 'ignore' or 'replace'

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

Check whether the string ends with obj, check if the specified range ends with obj if it is specified, or true if so, or false.

string.expandtabs(tabsize=8)

Turn the tab symbol in string string into a space, and the default number of spaces tabsize is 8.

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

Detects whether str is included in the string, if beg and end specify a range, then checks whether it is included in the specified range, or -1 is returned if the index value from the beginning is returned

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

It's the same as the find() method, except that if str doesn't report an exception in string.

string.isalnum()

Returns if the string has at least one character and all characters are letters or numbers

True, or false

string.isalpha()

True if the string has at least one character and all characters are letters.

Otherwise, false is returned

string.isdecimal()

If string contains only a hedding number, true is returned or False is returned.

string.isdigit()

If string contains only numbers, true is returned or False is returned.

string.islower()

True is returned if the string contains at least one case-sensitive character, and all of these (case-sensitive) characters are small case

string.isnumeric()

If only numeric characters are included in the string, True is returned, otherwise False is returned

string.isspace()

If only spaces are included in the string, true is returned, otherwise False is returned.

string.istitle()

True if string is titled (see title()), otherwise false is returned

string.isupper()

True is returned if the string contains at least one case-sensitive character, and all of these case-sensitive characters are capitals

string.join(seq)

Merges merges all the elements in seq (represented by strings) into a new string using string as a separator

string.ljust(width)

Returns a new string with the original string aligned to the left and filled with spaces to the length width

string.lower()

Convert all capital characters in string to small.

string.lstrip()

Cut off the space on the left side of the string

string.maketrans(intab, outtab])

The maketrans() method is used to create a conversion table for character mapping, and for the simplest way to accept two arguments, the first argument is a string, representing the characters that need to be converted, and the second argument is the target of the string representing the conversion.

max(str)

Returns the largest letter in the string str.

min(str)

Returns the smallest letter in the string str.

string.partition(str)

A bit like a combination of find() and split(), from the first position where str appears, the string string is divided into a 3-dollar group (string_pre_str, str, string_post_str), and if the string does not contain str then string_pre_str is string.

string.replace(str1, str2, num=string.count(str1))

Replace str1 in string with str2 and, if specified by num, no more than num.

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

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

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

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

string.rjust(width)

Returns a new string with the original string aligned to the right and filled with spaces to the length width

string.rpartition(str)

Similar to the partition() function, but starting from the right.

string.rstrip()

Remove the space at the end of the string.

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

The separator slice string is str, and if num has a specified value, only num substrings are separated

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

Separated by rows, returns a list that contains the rows as elements and slices only num rows if specified by num.

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

Check if the string starts with obj and returns True, otherwise false is returned. If beg and end specify values, check within the specified range.

string.strip([obj])

Perform lstrip() and rstrip() on string

string.swapcase()

Flip the case in the string

string.title()

Returns a "titled" string, which means that all words start in capitals and the rest of the letters are lowercase (see isitle())

string.translate(str, del="")

Convert the characters of the string based on the table given by str, which contains 256 characters.

The characters to filter out are placed in the del parameter

string.upper()

Convert lowercase letters in string to capital

string.zfill(width)

Returns a string with a length of width, the original string string is aligned to the right and is filled with 0 in front

string.isdecimal()

The isdecimal() method checks whether the string contains only adip characters. This method exists only in unicode objects.