I learned Python by myself. I learned strings and learned python.

Source: Internet
Author: User

I learned Python by myself. I learned strings and learned python.

I. String

(1) strings are the most common data types in Python. We can use single quotes or double quotes to create strings.

Str = 'Hello world! '

Str = "Hi Hao are you? "

(2) Python access strings can be accessed using square brackets.

Str = "Hello World! "

Print str [1] # Output e

Print str [] # output ello

This is no different from the method in the list.

(3) modify the string

Str = "Hello World! "

Print str [: 6] + "laowang" # output Hello laowang

(4) Remove spaces and special symbols

S. strip (). lstrip (). rstrip (',')

(5) connection string

Str1 = "hello"

Str2 = "laowang"

Str3 = str1 + str2

Print str3 # "hellolaowang"

"+" Can connect two strings

(6) locate the character

Str1 = "laowang"

Str2 = "w"

P = str1.index (str2)

Print p #3

(7) compare strings

Str1 = "hello"

Str2 = "Hello"

Print cmp (str1, str2) # returns 1

(8), String Length

Str = "hello"

Print len (str) # Return 5

(9) reverse string

Str = "hello"

Print str [:-1] # "olleh"

(10), connection string

Str = ","

List = ["python", "java", "javascript"]

Print str. join (list) # ["python", "java", "javascript"]

(11) Intercepting strings

Str = '000000 ′

Print str [0: 3] # capture the first to third characters

Print str [:] # capture all characters in a string

Print str [6:] # truncates the seventh character to the end

Print str [:-3] # capture the first to last three characters

Print str [2] # truncate the third character

Print str [-1] # capture the first to last character

     Print str [:-1] # create a string in the opposite order of the original string

Print str [-3:-1] # extract the characters before the last and last digits

Print str [-3:] # truncate the last third digit to the end

Print str [:-5:-3] # reverse truncation, with 3 as the step, from right to left

A newbie posted this article. I hope you can understand it.

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.