Beginner Tutorial from Python---string-related operations

Source: Internet
Author: User
Tags printable characters string format string methods


The string is the most commonly used data type in Python. We can use quotation marks to create strings.

Creating a string is simple, as long as you assign a value to the variable. For example:

=' Hello world! ' ="Python programming"  
Python accesses a value in a string

Python does not support single character types, and one character is also used as a string in Python.

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

#!/usr/bin/python=' Hello world! ' ="Python Programming"print "var1[0]:", var1[0]print"Var2[1:5" : ", var2[1:5]          

The result of the above instance execution:

var1[0]:  Hvar2[1:5]: ytho       
Python string update

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

#!/usr/bin/python=' Hello world! ' print"Updated String:-", var1[:6]+' Python '    

Result of the above instance execution

Python escape character

Python uses a backslash (\) to escape characters when special characters are needed in characters. As the following table:

Escape Character Description
\ (at end of line) Line continuation character
\\ Backslash symbol
\‘ Single quotation marks
\" Double quotes
\a Bell
\b BACKSPACE (Backspace)
\e Escape
\000 Empty
\ n Line break
\v Portrait tab
\ t Horizontal tab
\ r Enter
\f Page change
\oyy Octal number, the character represented by YY, for example: \o12 for newline
\xyy Hexadecimal number, the character represented by YY, for example: \x0a for line break
\other Other characters are output in normal format
Python string operator

The following table instance variable a value is the string "Hello" and the B variable value is "Python":

operator Description Example
+ String connection A + B output result: Hellopython
* Repeating output string A*2 Output Result: Hellohello
[] Getting characters in a string by index A[1] Output result e
[ : ] Intercept part of a string A[1:4] Output results ell
Inch Member operator-Returns TRUE if the string contains the given character H in a output result 1
Not in Member operator-Returns TRUE if the string does not contain the given character M Not in a output result 1
R/r Raw string-Raw string: all strings are used directly as literal meanings, without escaping special or non-printable characters. The original string has almost exactly the same syntax as a normal string, except that the first quotation mark of the string is preceded by the letter "R" (which can be case). print R ' \ n ' prints \ n and print R ' \ n' prints \ n
% format string Take a look at the next chapter
Python string formatting

Python supports the output of formatted strings. Although this may use a very complex expression, the most basic usage is to insert a value into a string that has the string format of%s.

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

The following example:

#!/usr/bin/pythonPrint"My name is%s and weight is%d kg!" %(' Zara ',+)       

The result of the above example output:

My is Zara and is + kg!      

Python string formatting symbols:


symbols Description
%c Formatting characters and their ASCII code
%s formatting strings
%d formatting integers
%u Formatting an unsigned integer
%o Formatting an unsigned octal number
%x formatting unsigned hexadecimal numbers
%x Format unsigned hexadecimal number (uppercase)
%f Format floating-point numbers to specify the precision after a decimal point
%e Format floating-point numbers with scientific notation
%E function with%e, format floating-point numbers with scientific notation
%g Shorthand for%f and%e
%G Shorthand for%f and%E
%p Format the address of a variable with hexadecimal number

Formatting operator Auxiliary directives:

symbols function
* Define width or decimal precision
- Used for left justification
+ Show plus sign (+) in front of positive number
<sp> Show spaces in front of positive numbers
# Displays 0 (' 0 ') before the octal number, preceded by ' 0x ' or ' 0X ' in hexadecimal (depending on ' x ' or ' x ')
0 The displayed number is preceded by ' 0 ' instead of the default space
% ' percent ' output a single '% '
(VAR) mapping variables (dictionary parameters)
M.N. M is the minimum total width displayed, and n is the number of digits after the decimal point (if available)
Python three-quote (triple quotes)

Three quotation marks in Python can be used to copy complex strings:

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

The syntax for a triple quotation mark is a pair of consecutive single or double quotes (usually paired).

>>>=' Hi there '>>># repr ()' Hi\nthere '>>>Print # str ()         

Three quotes allow programmers to escape from the mire of quotes and special strings, keeping a small piece of string in the form of what is known as WYSIWYG.

A typical use case is that when you need a piece of HTML or SQL, a special string escape is cumbersome when you use a string combination.

="' 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 mark indicates that a Unicode string is created here. If you want to add 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 ID indicates that a Unicode character (a blank space) with encoded values of 0x0020 is inserted at the given location.

Python string built-in functions

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

These methods implement most of the methods of the string module, as shown in the following table, which lists the currently supported methods for string literals, all of which contain support for Unicode, and some are even specifically for Unicode.

Method Description

String.capitalize ()

Capitalize the first character of a string (width)

Returns the center of the original string and fills the new string with a space of length width

String.count (str, beg=0, End=len (String))

Returns the number of occurrences of STR in a string, if beg or end specifies that the number of STR occurrences in the specified range is returned

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

Decodes a string in the encoded format specified by encoding, if an error defaults to a ValueError exception unless errors specifies ' ignore ' or ' replace '

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

Encodes a string in the encoding format specified by encoding, if an error defaults to a ValueError exception unless errors specifies ' ignore ' or ' replace '

String.endswith (obj, beg=0, End=len (String))

Checks whether the string ends with obj, or returns False if beg or end specifies whether to end with obj in the specified range, or True if it is.

String.expandtabs (tabsize=8)

Turns the tab symbol in string strings to a space, and the default number of spaces Tabsize is 8.

String.find (str, beg=0, End=len (String))

Detects if STR is contained in a string, and if beg and end specify a range, the check is contained within the specified range, and returns 1 if the index value is returned.

String.index (str, beg=0, End=len (String))

Just like the Find () method, only if STR does not report an exception in string.

String.isalnum ()

If the string has at least one character and all characters are letters or numbers, return

Return True, otherwise False

String.isalpha ()

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

otherwise returns False

String.isdecimal ()

Returns True if the string contains only a decimal number, otherwise False.

String.isdigit ()

Returns True if the string contains only a number, otherwise False.

String.islower ()

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

String.isnumeric ()

Returns True if the string contains only numeric characters, otherwise False

String.isspace ()

Returns True if the string contains only spaces, otherwise False is returned.

String.istitle ()

Returns True if string is heading (see Title ()), otherwise False

String.isupper ()

Returns True if the string contains at least one case-sensitive character, and all of these (case-sensitive) characters are uppercase, otherwise False

String.Join (seq)

Merges (concatenates) merges all the elements in the SEQ (the string representation) into a new string as a string delimiter

String.ljust (width)

Returns the left alignment of an original string and fills the new string with the width of length with a space

String.Lower ()

Converts all uppercase characters in a string to lowercase.

String.lstrip ()

Truncate the left space of a string

String.maketrans (Intab, Outtab])

The Maketrans () method is used to create a conversion table of character mappings, for the simplest invocation of two parameters, the first argument is a string that represents the character that needs to be converted, and the second argument is the target of the string representation of the transformation.

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 the combination of find () and split (), from the first position where Str appears, divide the string into a 3-element tuple (STRING_PRE_STR,STR,STRING_POST_STR), if string STR is not included in the STRING_PRE_STR = = string.

String.Replace (str1, str2, Num=string.count (STR1))

Replace the str1 in string with the str2, if NUM is specified, the replacement is no more than num times.

String.rfind (str, Beg=0,end=len (String))

Similar to the Find () function, it is just looking from the right.

String.rindex (str, Beg=0,end=len (String))

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

String.rjust (width)

Returns the right alignment of the original string and fills the new string with the width of the length with a space

String.rpartition (str)

Similar to the partition () function, it is just looking from the right.

String.rstrip ()

Removes a space at the end of a string string.

String.Split (str= "", Num=string.count (str))

Slice string with a delimiter of STR, if NUM has a specified value, only the NUM substring is delimited

String.splitlines (Num=string.count (' \ n '))

Returns a list that contains rows as elements, separated by rows, and if num specifies that only num rows are sliced.

String.startswith (obj, Beg=0,end=len (string))

Checks whether the string starts with obj, returns True, or False. If beg and end specify a value, the check is within the specified range.

String.strip ([obj])

Execute Lstrip () and Rstrip () on string

String.swapcase ()

Flip the case in a string

String.title ()

A string that returns "header", meaning that all words start with uppercase and the remaining letters are lowercase (see istitle ())

String.translate (str, del= "")

Converts a string of characters according to 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 uppercase

String.zfill (width)

Returns a string of length width, the original string is right-aligned, and the front padding is 0

String.isdecimal ()

The Isdecimal () method checks whether a string contains only decimal characters. This method exists only in Unicode objects.

Beginner Tutorial from Python---string-related operations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.