一、String的表示方法
1.声明一个String可以用" "或者' ',两者没有差别,为了方便使用,可以在字符串内容中含有 ' 时用" ",同理也可以在含有 " 时用' ',避免使用转义字符。
# Strings are enclosed in quotes
name = 'Scott Rixner'
university = "Rice"
print(name)
print(university)
2.希望保留换行、空格等格式的较为复杂的string,可以用''' '''或者""" """声明。
e.g.
# Multiline strings use triple quotes
address = '''Rice University
Houston, TX
'''
# First Fig by Edna St. Vincent Millay
poem = """My candle burns at both ends;
It will not last the night;
But ah, my foes, and oh, my friends---
It gives a lovely light!
"""
print("")
print("Address")
print("=======")
print(address)
print("First Fig")
print("=========")
print(poem)
打印结果如下,需要注意的是这里打印出的空行是因为在字符串文字的结尾没有直接使用''',而是先换行再使用的''',因此换行符也包含在字符串内容中,一并打印在输出结果里了。
3.String中可以包含的一些character示例,包括字母、数字、特殊符号、转义字符等。
# Characters
chars = "abc'DEF*&$"
print(chars)
chars2 = '\t"abc"\ndef\''
print(chars2)
4.String之间的运算,加法即简单相加成为一个新的String,乘法相当于把一个String重复叠加数次成为新的String。
# String "arithmetic"
name = 'Scott Rixner'
university = "Rice"
print("Concatenating strings")
name_and_uni = name + " " + university
print(name_and_uni)
print("")
print("")
print("Repeating strings")
lots_o_rice = university * 4
print(lots_o_rice)
输出结果为:
5.将其他数据类型转换为String的str()函数。当我们希望把一个数值添加到字符串的末尾时,无法直接使用+号,因为数值类型和String类型的相加是没有意义的,需要先用str()函数把数值类型转换为字符串类型,再与原字符串相加。
# Using str
num = 3.87
strnum = str(num)
print("number: " + strnum)
注:此处如果直接使用print("number: " + num)将会报错。
二、String的index使用方法
1.可以使用index直接取字符串中固定位置的字符。
-phrase[0]表示取phrase字符串中的第一个字符。
-Python没有char数据类型,当我们对phrase[0]使用type()函数【python内置函数,返回输入的变量类型】时,它仍然属于String类型。
-len()函数可以获取一个字符串的大小。
"""
String indexing examples.
"""
phrase = "Python is great!"
# first character
print(phrase[0])
# fourth character
fourth = phrase[3]
print(fourth)
print(type(phrase))
print(type(fourth))
# length of string
phraselen = len(phrase)
print(phraselen)
输出结果为:
2.使用负数index可以读取String中倒数的字符,index取-n时,可以取到倒数第n位的字符。e.g.
phrase = "Python is great!"
# last character
print(phrase[phraselen - 1])
print(phrase[-1])
# thirteenth from last (fourth) character
print(phrase[-13])
- phraselen=16,因此phrase[phraselen-1]为phrase[15],因为index取0时表示字符串第一位,取15时即表示第16位,也就是该字符串的最后一位
-phrase[-1]是取字符串最后一位更快捷的办法
-phrase[-13]是取字符串的倒数13位字符,即正数第4位字符。
输出结果为:
为了更直观的表现index取正数和负数时取到的字符,给出下面的案例:
string = 'abcde'
在这个声明中,不同character对应的正负index如下:
character a b c d e
pos index 0 1 2 3 4
neg index -5 -4 -3 -2 -1
三、在String中搜索内容
1.find()和index()函数都可以用来在String中搜索是否有匹配的片段
"""
String searching examples.
"""
sentence = "When I tell you pick up the " + \
"left rock, it will be the " + \
"right one, and then only " + \
"the right rock will be left."
# Finding strings within strings
firstleft = sentence.find("left")
print(firstleft, sentence[firstleft])
lastleft = sentence.rfind("left")
print(lastleft, sentence[lastleft])
print("")
firstright = sentence.index("right")
print(firstright, sentence[firstright])
lastright = sentence.rindex("right")
print(lastright, sentence[lastright])
-find()函数返回正向搜索第一个找到的匹配内容的开头字符的index
-rfind()函数从字符串的结尾开始搜索,返回逆向搜索第一个找到的匹配内容的开头字符的index
-在这个例子中,find()与index()作用一致,rfind()与rindex()作用也一致
输出结果为:
2.find与index的区别仅在于:在String中搜索时找不到匹配的内容,即搜索失败时,使用find()函数会返回值-1,而使用index会报错。(rfind与rindex同理)
e.g.1执行下面的代码会得到输出值-1
sentence = "When I tell you pick up the " + \
"left rock, it will be the " + \
"right one, and then only " + \
"the right rock will be left."
firstrixner1 = sentence.find("Rixner")
print(firstrixner1)
e.g.2执行下面的代码会报错
sentence = "When I tell you pick up the " + \
"left rock, it will be the " + \
"right one, and then only " + \
"the right rock will be left."
firstrixner2 = sentence.index("Rixner")
print(firstrixner2)
3.count()函数可以检测输入内容在String中出现的次数
sentence = "When I tell you pick up the " + \
"left rock, it will be the " + \
"right one, and then only " + \
"the right rock will be left."
print("Counting substrings")
print("Number of lefts:", sentence.count("left"))
print("Number of apples:", sentence.count("apple"))
-"left"在原字符串中出现了2次,"apple"没有出现
输出结果为:
4.startswith()和endswith()函数可以检查字符串是否以输入内容开头或者结尾,返回True或False
sentence = "When I tell you pick up the " + \
"left rock, it will be the " + \
"right one, and then only " + \
"the right rock will be left."
print(sentence.startswith("When"))
print(sentence.endswith("The end."))
输出结果为:
5.一个课后习题中发现的内容,可以用in判断字符串中是否有指定内容,返回值为True或False。
s = "Alex Clover"
ret = "Clover" in s
print(ret)
输出结果为True。
四、切割字符串(取字符串中的一部分内容)
"""
Slicing strings.
"""
word = "everything"
# Selecting substrings
print(word[1:5]) #输出结果为very
print(word[5:9]) #输出结果为thin
# Open ended slices
print(word[5:]) #输出结果为thing
print(word[:4]) #输出结果为ever
# Using negative indices
print(word[-3:]) #输出结果为ing
print(word[2:-3]) #输出结果为eryth
# Indexing past the end
print(word[8:20]) #输出结果为ng
print("$" + word[22:29] + "^") #输出结果为$^
# Empty slices
print(word[6:6]) #输出结果为空,但不会报错
print(word[4:2]) #输出结果为空,但不会报错
-用word[1:5]的形式,可以指定字符串中想要内容的起始和结尾字符的index,将想要的部分提取出来
-word[m:n]表示从index m开始截取,一直取到index为n-1的字符,不取index为n的字符
-word[5:]表示从index 5的字符开始截取,一直截取到字符串末尾;同理,word[:4]表示从头开始截取,一直截取到index为3的字符,不取index为4的字符。
-截取字符串也可以用负数index。word[-3:]表示从倒数第三个字符开始截取到字符串最后。
-在截取的区间中,如果index超过了字符串的范围不会报错。word[8:20]与word[8:]的效果一样,因为20超过了字符串的最大长度,直接截取到字符串最后一位。(此处可以把字符串理解为无限长,前面为有效内容,后面都为空)
-如果截取的区间不是有效区间,比如[6:6],[4:2]等,只会输出空,但程序不会报错。
最后附上课后练习与课程链接:
https://www.coursera.org/learn/python-representation/supplement/EwIGa/practice-exercises-for-strings