Python学习[01]

来源:互联网 发布:李世宏dota2 知乎 编辑:程序博客网 时间:2024/06/01 18:58

[01]Learn Python——Strings & Console Output


1.Strings

A string can contain letters, numbers, and symbols.

name = "Ryan"age = "19"food = "cheese"

2.Access by Index

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

"""The string "PYTHON" has six characters,numbered 0 to 5, as shown below:+---+---+---+---+---+---+| P | Y | T | H | O | N |+---+---+---+---+---+---+  0   1   2   3   4   5So if you wanted "Y", you could just type"PYTHON"[1] (always start counting from 0!)"""c = "cats"[0]n = "Ryan"[3]

3.String methods

Now that we know how to store strings, let’s see how we can change them using string methods.

String methods let you perform specific tasks for strings.

We’ll focus on four string methods:

1.len()

parrot = "Norwegian Blue"print len(parrot)>>>14

2.lower()

parrot = "Norwegian Blue"print parrot.lower() >>>norwegian blue

3.upper()

parrot = "norwegian blue"print parrot.upper()>>>NORWEGIAN BLUE

4.str()

pi = 3.14print str(pi)>>>"3.14"

4.Dot Notation

lion = "roar"len(lion)lion.upper()

Methods that use dot notation only work with strings.

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

5.String Concatenation

You know about strings, and you know about arithmetic operators. Now let’s combine the two!

print "Life " + "of " + "Brian">>>Life of Brian

Sometimes you need to combine a string with something that isn’t a string. In order to do that, you have to convert the non-string into a string.

print "I have " + str(2) + " coconuts!">>>I have 2 coconuts!

6.String Formatting with %, Part 1

When you want to print a variable with a string, there is a better method than concatenating strings together.

name = "Mike"print "Hello %s" % (name)>>>Hello Mike
string_1 = "Camelot"string_2 = "place"print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)>>>Let's not go to Camelot. 'Tis a silly place.
原创粉丝点击