home PYTHONJAVA
 

Python string

Strings are the most commonly used data types in Python. We can use quotation marks ( ' or " ) to create a string. Creating a string is as simple as assigning a value to a variable. E.g:

The above example execution results:

var1[0]: W
Var2[1:8]: welookups

Python string update

You can intercept a part of a string and splicing it with other fields, as in the following example:

Instance (Python 3.0+)

#!/usr/bin/python3 var1 = 'Hello World!' print ("Updated string: ", var1[:8] + 'welookups!')

The above example execution results

updated strings :  Hello welookups !

Python escape character

Python uses a backslash (\) escape character when you need to use special characters in characters. As shown below:

escape character description
\(at the end of the line) Continuous character
\\ backslash symbol
\' single quotes
\" double quotes
\a Bell
\b Backspace
\e escape
\000 empty
\n Line break
\v Vertical Tabs
\t Horizontal tabs
\r Enter
\f Change page
\oyy octal number, the character represented by yy, for example: \o12 stands for line break
\xyy hexadecimal number, the character represented by yy, for example: \x0a stands for line break
\other Other characters are output in normal format

Python string operator

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

OperatorDescriptionInstance
+String connection a + b Output: HelloPython
*Repeat output string a*2 Output: HelloHello
[]Get the characters in the string by index a[1] Output e
[ : ] Take a section of the string and follow the Left Closed Right principle, str[0,2] does not contain the third character. a[1:4] Output ell
inMember operator - Returns True if the string contains the given character 'H' in a Outputs True
not in member operator - returns True if the string does not contain the given character 'M' not in a output True
r/ROriginal String - Original String: All strings are used literally, without special characters that can be escaped or not printed. The original string has almost exactly the same syntax as a normal string, except that the letter r (which can be capitalized) is preceded by the first quotation mark in the string.
print( r'\n' ) 
print( R'\n' )
%Format string Please see the next section.

Instance(Python 3.0+)

#!/usr/bin/python3 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 In the variable a in") a = "Hello" b = "Python" else : print("H Not in variable a ") if( "M" not in a) : print("M Not in variable a in") else : print("M In the variable a in") print (r'\n') print (R'\n')

The output of the above example is:

a + b Output result: HelloPython
a * 2 Output result: HelloHello
a[1] Output result: e
a[1:4] Output result: ell
H In the variable a in
M Not in variable a in
\n
\n

Python string formatting

Python supports the output of formatted strings. Although this may use very complex expressions, the most basic use 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.

Instance (Python 3.0+)

#!/usr/bin/python3 print ("My name is %s %d this year!" % ('Welookups', 10))

The output of the above example:

My name is welookups this year 10 year old!

python string formatting symbol:

    symbol  number Description      ; %c Formatting characters and their ASCII code       %s< /font> Format String      %d  Format integers      %u Format unsigned integer       ; %o Format unsigned octal number      %x Format unsigned hexadecimal number      %X  Format unsigned hexadecimal (uppercase)      %f Format floating point numbers to specify the precision after the decimal point      %e Format floating point numbers using scientific notation      %E  acts like %e, formatting floating point numbers using scientific notation      %g %f and %e shorthand      %G %f and %E shorthand      %p Format the address of the variable with a hexadecimal number

Format operator helper instructions:

in front of the positive number
symbolfunction
*Define width or decimal precision
-Use left alignment
+Show the plus sign ( + )
<sp>Show spaces before positive numbers
# displays zero ('0') in front of the octal number and '0x' or '0X' in front of the hexadecimal (depending on whether it is 'x' or 'X')
0 The displayed number is padded with '0' instead of the default space
% '%%' outputs a single '%'
(var)Map Variables (Dictionary Parameters)
m.n. m is the minimum total width of the display, and n is the number of digits after the decimal point (if available)

Beginning with Python 2.6, a new function for formatting strings has been added.

*Define width or decimal precision -Use left alignment +Show the plus sign ( + ) in front of the positive number <sp>Show spaces before positive numbers # displays zero ('0') in front of the octal number and '0x' or '0X' in front of the hexadecimal (depending on whether it is 'x' or 'X') 0 The displayed number is padded with '0' instead of the default space % '%%' outputs a single '%' (var)Map Variables (Dictionary Parameters) m.n. m is the minimum total width of the display, and n is the number of digits after the decimal point (if available)

Beginning with Python 2.6, a new function for formatting strings has been added

The above example execution result is:

This is an instance of a multi-line string
Multiple-line strings can use tabs
TAB ( ). 
You can also use line breaks [
  ]. 

Three quotes free the programmer from the quagmire of quotes and special strings, keeping a small string of formatting from start to finish in the so-called WYSIWYG (what you see is what you get) format.

A typical use case is that when you need a piece of HTML or SQL, then 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

In Python 2, normal strings are stored in 8-bit ASCII, while Unicode strings are stored as 16-bit unicode strings, which can represent more character sets. The syntax used is to prefix the string with u.

In Python 3, all strings are Unicode strings.



Python's string built-in function

Python's string built-in functions are as follows:

on a string
serial numbermethod and description
1

capitalize()
The first string Convert characters to uppercase

2

center(width, fillchar)


Returns a specified width width centered string, fillchar is the padded character, defaults to a space.
3

count(str, beg= 0,end=len(string))< /a>


Returns the number of occurrences of str in string. If beg or end specifies the number of occurrences of str within the specified range
4

bytes.decode(encoding="utf-8", errors="strict ")


There is no decode method in Python3, but we can use the decode() method of the bytes object to decode the given bytes object, which can be encoded by str.encode() return.
5

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


Encodes the string in the encoding format specified by encoding. If an error occurs, a ValueError exception is reported by default, unless errors specifies 'ignore' or 'replace'
6

endswith(suffix, beg=0, end=len(string))< /a>
Check if the string ends with obj. If beg or end specifies, check if the specified range ends with obj. If yes, return True, otherwise return False.

7

expandtabs(tabsize=8)


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

find(str, beg=0, end=len(string))< /a>


Check if str is included in the string. If the range beg and end are specified, check if it is included in the specified range, if it contains the index value that returns the start, otherwise return -1
9

index(str, beg=0, end=len(string))< /a>


Same as the find() method, except that if str is not in the string, an exception will be reported.
10

isalnum()


If the character The string has at least one character and all characters are letters or numbers. Go back to True, otherwise return False
11

isalpha()


If the characters Returns a string if the string has at least one character and all characters are letters. Otherwise return False
12

isdigit()


If the character Returns true if the string contains only numbers, otherwise returns False..
13

islower()


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

isnumeric()


If the character Returns True if the string contains only numeric characters, otherwise returns False
15

isspace()


If the character Returns True if the string contains only white space, otherwise returns False.
16

istitle()


Returns True if the string is headerd (see title()), otherwise returns False
17

isupper()


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

join(seq)


Specify a string as a separator to combine all the elements in seq (a string representation) into a new string
19

len(string)


Back String length
20

ljust(width[, fillchar])


Returns an original string left-aligned and fills a new string of length width with fillchar, which defaults to a space.
21

lower()


Converting characters All uppercase characters in the string are lowercase.
22

lstrip()


Truncate A space to the left of the string or a specified character.
23

maketrans()


Creating characters The converted conversion table, for the simplest way to accept two parameters, the first parameter is a string, which represents the character to be converted, and the second parameter is also a string representing the target of the conversion.
24

max(str)


Back The largest letter in the string str.
25

min(str)


Back The smallest letter in the string str.
26

replace(old, new [, max])
Replace str1 in the string with str2, and if max specifies, replace no more than max times.

27

rfind(str, beg=0,end=len(string))< /a>


Similar to the find() function, but look for it from the right.
28

rindex( str, beg=0, end=len(string))< /a>


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

rjust(width,[, fillchar])


Returns an original string right-aligned and fills a new string of length width with fillchar (default space)
30

rstrip()


Delete characters The space at the end of the string string.
31

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


num=string.count(str)) Intercept the string with str as the separator. If num has the specified value, only num+1 substrings are intercepted
32

splitlines([keepends])


Separate by line ('\r', '\r\n', \n'), return a list containing the lines as elements, if the parameter keepends is False, no line breaks, if True, leave line breaks .
33

startswith(substr, beg=0,end=len(string))< /a>


Checks if the string starts with the specified substring substr, and returns True, otherwise returns False. If beg and end specify a value, check within the specified range.
34

strip([chars])


Execute lstrip() and rstrip()
35

swapcase()


will character Convert uppercase letters to lowercase and lowercase to uppercase
36

title()


Back" The titled string, that is, all words start with uppercase, and the rest of the letters are lowercase (see istitle())
37

translate(table, deletechars="")


Convert string characters according to the table given by str (containing 256 characters) The characters to be filtered are placed in the deletechars parameter
38

upper()


Lowercase letters in the conversion string are uppercase
39

zfill (width)


Back A string of length length, the original string is right-aligned, padded with 0
40

isdecimal()


Checks if the string contains only decimal characters, if it returns true, otherwise it returns false.





welookups is optimized for learning.© welookups 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.welookups