week 1-learn python 2

strings

A string can contain letters, numbers, and symbols.

escaping characters


escaping characters

access by index

Each character in a string is assigned a number. This number is called the index.

    statement#返回该字符串索引对应的值

    c = "cats"[0]

    n = "Ryan"[3]

Python indices begin counting at 0

String methods

String methods let you perform specific tasks for strings.

We’ll focus on four string methods:

len() # which gets the length (the number of characters) of a string

lower()#  get rid of all the capitalization in your strings. You call lower() like so: 全部小写

    statement

 "Ryan".lower()

    which will return "ryan"

upper() # A similar method exists to make a string completely upper case.

str()

Dot Notation

Methods that use dot notation only work with strings.

On the other hand, len() and str() can work on other data types.

Printing Strings

The area where we’ve been writing our code is called the editor.

The console (the window to the right of the editor) is where the results of your code is shown.

String Concatenation

+

Explicit String Conversion

str()

String Formatting with %, Part 1

     statement

    name = "Mike"

    print "Hello %s" % (name)

# The % operator after the string is used to combine a string with variables. The % operator will replace the %s in the string with the string variable that comes after it.这个百分号不止能代表一个变量,(You need the same number of %s terms in a string as the number of variables in parentheses:)例如

    statement

    string_1 = "Camelot"

    string_2 = "place"

    print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)

If you’d like to print a variable that is an integer, you can “pad” it with zeros using %02d. The 0 means “pad with zeros”, the 2 means to pad to 2 characters wide, and the d means the number is a signed integer (can be positive or negative).

    statement

    day = 6

    print "03 - %s - 2019" %  (day)

    # 03 - 6 - 2019

    print "03 - %02d - 2019" % (day)

    # 03 - 06 - 2019

    print "Ah, so your name is %s, your quest is %s, " \

    "and your favorite color is %s." %(name, quest, color)

#其中\的作用暂时未知

你可能感兴趣的:(week 1-learn python 2)