接上一篇博文,这章讲string

3 string

3.1 string的连接

hello = "Hello"
world = 'World'

hello_world = hello+' '+world
print(hello_world)      # Note: you should print "Hello World"

string的拼接直接使用 ‘+’运算符实现,并可在中间使用“ ”来加入字符串

3.2 string的自复制

hello = "hello"
ten_of_hellos = hello * 10
print(ten_of_hellos)
#output hellohellohellohellohellohellohellohellohellohello
#这里将hello复制了十遍(包含原有hello共10个)

3.3 string 脚标访问

python = "Python"
print("h " + python[3])     # Note: string indexing starts with 0

p_letter = python[0]
print(p_letter)
#output 
#h h 第一个h为直接输入,第二个h是对string通过脚标访问
#P 通过脚标访问输出

3.3 string 倒序访问

long_string = "This is a very long string!"
exclamation = long_string[-1]
print(exclamation)
#output !
#输出为'!'是倒数第一个

3.4 string 的截取

monty_python = "Monty Python"
monty = monty_python[:5]+'!'
# one or both index could be dropped. monty_python[:5] is equal to monty_python[0:5]
print(monty)
python = monty_python[6:]
print(python)
#output Monty!
#[:5]是截取0,1,2,3,4 不包含脚标5指向的‘ ’
#Python 
#[6:]是从脚标6到最后一位

3.5 判断string是否包含特定字符串

ice_cream = "ice cream"
print("cream" in ice_cream)    # print boolean result directly

contains = "ice" in ice_cream
print(contains)
#output 
#True
#True
#in函数会返回一个bool数,判断in后string是否包含in前string

3.6 计算字符串长度

phrase = """
It is a really long string
triple-quoted strings are used
to define multi-line strings
"""
#len(str) 返回str长度
#int 做转换,若len为奇数时除不尽会产生小数
first_half = phrase[:int(len(phrase)/2)]
print(first_half)
#output It is a really long string
#triple-quoted st

3.7 print时输出特殊字符

dont_worry = "Don't worry about apostrophes"
print(dont_worry)
print("\"Sweet\" is an ice-cream")
print('The name of this ice-cream is "Sweet\'n\'Tasty"')
#output 
#Don't worry about apostrophes string原样输出
#"Sweet" is an ice-cream 通过 \ 输出特殊字符"
#The name of this ice-cream is "Sweet'n'Tasty"

3.8 string 大小写转换

monty_python = "Monty Python"
print(monty_python)
print(monty_python.lower())    # print lower-cased version of the string
print(monty_python.upper())
print(monty_python)
#output 
#Monty Python
#monty python 全部小写
#MONTY PYTHON 全部大写
#Monty Python 原始string并没有改变,说明上两个是返回两个转换了大小写的string

3.9 print时替换%的数据类型

name = "John"
print("Hello, PyCharm! My name is %s!" % name)     # Note: %s is inside the string, % is after the string
years = 25
print("I'm %d years old." % years)
print("I'm %d years old, My name is %s!" % (years,name))
#要替换string中多个元素时,通过 %(a,b,c)来实现

%所对应的转换 含义

d,i 带符号的十进制整数
o 不带符号的八进制
u 不带符号的十进制
x 不带符号的十六进制(小写)
X 不带符号的十六进制(大写)
e 科学计数法表示的浮点数(小写)
E 科学计数法表示的浮点数(大写)
f,F 十进制浮点数
g 如果指数大于-4或者小于精度值则和e相同,其他情况和f相同
G 如果指数大于-4或者小于精度值则和E相同,其他情况和F相同
C 单字符(接受整数或者单字符字符串)
r 字符串(使用repr转换任意python对象)
s 字符串(使用str转换任意python对象)

4 数据结构