Python3 string (7), python3 string

Source: Internet
Author: User
Tags natural string

Python3 string (7), python3 string

A string is the most common data type in Python. We can use quotation marks ('or ") to create strings.

It is easy to create a string by assigning a value to the variable.

  • In python, single quotes and double quotes are identical.
  • You can use three quotation marks (''' or ") to specify a multi-line string.
  • Escape Character '\'
  • Natural string, by adding r or R before the string. For example, if r "this is a line with \ n", \ n is displayed, not a line break.
  • Python allows you to process unicode strings with the prefix u or U, such as u "this is an unicode string ".
  • The string is unchangeable.
  • Cascade strings literally. For example, "this" "is" "string" is automatically converted to this is string.
  • Python does not have a separate character type. A character is a string of 1 characters.
  • The Python string cannot be changed. Assign a value to an index location. For example, word [0] = 'M' may cause an error.
  • The backslash can be used for escape, and r can be used to prevent the backslash from being escaped.
  • Strings can be connected together using the + operator, which is repeated using the * operator.
  • There are two indexing methods for strings in Python: 0 from left to right and-1 from right to left.

For example:

1 word = 'string' 2 sentence = "this is a sentence. "3 paragraph =" "This is a paragraph, 4 can be composed of multiple lines """
1 >>> print('Ru\noob')2 Ru3 oob4 >>> print(r'Ru\noob')5 Ru\noob6 >>>
1 #! /Usr/bin/python3 2 3 str = 'runoob' 4 5 print (str) # output string 6 print (str [0:-1]) # output all the characters from the first to the second to the last 7 print (str [0]) # output the first character of the string 8 print (str []) # output 9 print (str [2:]) from the third to the fifth character # output 10 print (str * 2) after the third character) # output string 11 print (str + "TEST") twice # connection string

The following results are output when the above program is executed:

1 Runoob2 Runoo3 R4 noo5 noob6 RunoobRunoob7 RunoobTEST
Value in the Python access string

Python does not support the single character type. A single character is also used as a string in Python.

Python can use square brackets to intercept a substring, as shown in the following example:

1 #!/usr/bin/python32  3 var1 = 'Hello World!'4 var2 = "Runoob"5  6 print ("var1[0]: ", var1[0])7 print ("var2[1:5]: ", var2[1:5])

Execution result of the above instance:

1 var1[0]:  H2 var2[1:5]:  unoo
Python string update

You can take part of the string and splice it with other fields, as shown in the following example:

1 #! /Usr/bin/python32 3 var1 = 'Hello World! '4 5 print ("updated string:", var1 [: 6] + 'runoob! ')

Execution result of the above instance:

1 Updated string: Hello Runoob!
Python escape characters

When special characters are needed, python uses a backslash (\) to escape the characters. See the following table:

Python string Operators

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

 

1 #! /Usr/bin/python3 2 3 a = "Hello" 4 B = "Python" 5 6 print ("a + B output result:", a + B) 7 print ("a * 2 output result:", a * 2) 8 print ("a [1] output result:", a [1]) 9 print ("a [] output result:", a []) 10 11 if ("H" in a): 12 print ("H in variable ") 13 else: 14 print ("H is not in variable a") 15 16 if ("M" not in a): 17 print ("M is not in variable a") 18 else: 19 print ("M in variable a") 20 21 print (R' \ n') 22 print (R' \ n ')

The output result of the above instance is:

1 a + B output result: HelloPython2 a * 2 output result: HelloHello3 a [1] output result: e4 a [] output result: ell5 H in variable a 6 M not in variable a 7 \ n8 \ n
Python string formatting

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

1 #! /Usr/bin/python32 3 print ("My name is % s % d years old! "% ('Xiaoming ', 10 ))

Output result of the above instance:

1. My name is James, 10 years old!

Python string formatting symbol:

Auxiliary instructions for formatting operators:

In Python2.6, a new function str. format () is added, which enhances the string Formatting Function.

 1 Name = input("Name:") 2 Age = int(input("Age:")) 3 Job = input("Job:") 4 Salary = int(input("Salary:")) 5  6 msg = """ 7 =======Info of %s=========== 8 Name: %s 9 Age: %d10 Job: %s11 Salary: %d12 ========= end ===============13 """ % (Name, Name, Age, Job, Salary)14 15 print(msg)
View Code

The running result is:

 1 Name:lhm 2 Age:23 3 Job:coding 4 Salary:5699 5  6 =======Info of lhm=========== 7 Name: lhm 8 Age: 23 9 Job: coding10 Salary: 569911 ========= end ===============
View CodeUnicode string

In Python2, common strings are stored in 8-bit ASCII code, while Unicode strings are stored as 16-bit unicode strings, which can represent more character sets. The syntax used is to prefix the string.U.

In Python3, all strings are Unicode strings.

Python string built-in functions

Common built-in functions of Python strings are as follows:

Serial number Method and description
1

Capitalize ()
Converts the first character of a string to uppercase.

2

Center (width, fillchar)


Returns a string with the specified width and width centered. fillchar is a filled character. The default value is space.
3

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


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

Bytes. decode (encoding = "UTF-8", errors = "strict ")


Python3 does not have the decode method, but we can use the decode () method of the bytes object to decode the given bytes object. This bytes object can be encoded and returned by str. encode.
5

Encode (encoding = 'utf-8', errors = 'strict ')


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

Endswith (suffix, beg = 0, end = len (string ))
Check whether the string ends with obj. If beg or end is specified, check whether the string ends with obj in the specified range. If yes, return True; otherwise, return False.

7

Expandtabs (tabsize = 8)


Convert the tab character in the string to a space. The default number of spaces for the tab character is 8.
8

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


Checks whether str is included in the string. If the specified range is beg and end, checks whether it is included in the specified range. If the range is included, returns the starting index value; otherwise, returns-1.
9

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


Like the find () method, but if str is not in the string, an exception is reported.
10

Isalnum ()


Returns True if the string contains at least one character and all characters are letters or numbers. Otherwise, returns False.
11

Isalpha ()


Returns True if the string contains at least one character and all characters are letters; otherwise, returns False.
12

Isdigit ()


Returns True if the string contains only numbers. Otherwise, returns False ..
13

Islower ()


Returns True if the string contains at least one case-sensitive character, and all these (case-sensitive) characters are lowercase. Otherwise, returns False.
14

Isnumeric ()


Returns True if the string contains only numeric characters; otherwise, returns False.
15

Isspace ()


If the string contains only white spaces, True is returned; otherwise, False is returned.
16

Istitle ()


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

Isupper ()


True is returned if the string contains at least one case-sensitive character and all these (case-sensitive) characters are uppercase. Otherwise, False is returned.
18

Join (seq)


Use a specified string as the separator to combine all elements (represented by strings) in seq into a new string.
19

Len (string)


Returns the string length.
20

Ljust (width [, fillchar])


Returns a new string with the left alignment of the original string and fills in the width with fillchar. fillchar is a space by default.
21

Lower ()


All uppercase characters in the conversion string are lowercase.
22

Lstrip ()


Truncates spaces or specified characters on the left of the string.
23

Maketrans ()


Create a character ing conversion table. For the simplest call method to accept two parameters, the first parameter is a string, indicating the characters to be converted, and the second parameter is also the conversion target of the string.
24

Max (str)


Returns the largest letter in the str string.
25

Min (str)


Returns the smallest letter in the str string.
26

Replace (old, new [, max])


Replace str1 with str2. If max is specified, it cannot exceed max.
27

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


Similar to the find () function, but the query starts from the right side.
28

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


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

Must ust (width, [, fillchar])


Returns a new string with the right alignment of the original string and fills in the width with fillchar (default space ).
30

Rstrip ()


Removes spaces at the end of a string.
31

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


Num = string. count (str) truncates a string using the str separator. If num has a specified value, only the num sub-string is intercepted.
32

Splitlines ([keepends])


Returns a list containing all rows as elements separated by rows ('\ R',' \ r \ n', \ n'). If the keepends parameter is False, it does not contain line breaks, if this parameter is set to True, the linefeed is retained.
33

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


Check whether the string starts with obj. If yes, True is returned. Otherwise, False is returned. If the beg and end values are specified, check the values within the specified range.
34

Strip ([chars])


Execute lstrip () and rstrip () on the string ()
35

Swapcase ()


Converts uppercase to lowercase letters and lowercase letters to uppercase letters.
36

Title ()


Returns the title string, that is, all words start with an uppercase letter, and all other letters are lowercase letters (see istitle ())
37

Translate (table, deletechars = "")


Convert string Characters Based on the table (including 256 characters) given by str, and put the characters to be filtered out into the deletechars Parameter
38

Upper ()


Converts lowercase letters in a string to uppercase letters.
39

Zfill (width)


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

Isdecimal ()


Check whether the string contains only decimal characters. If it is true, otherwise false is returned.

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: info-contact@alibabacloud.com 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.