一、字符串
字符串用双引号""或者单引号''表示,双引号里面可以只有单引号,单引号里面可以只有双引号
''It's good" 'You are a "Good" man'
当字符串里既含有单引号又含有双引号时:
'I\'m a \"good\" student' #其中\'表示单引号,\"表示双引号
\称作转译字符,除了用来表示引号,还有用来:
\\表示字符串中的\
\n表示字符串中的换行
\表示代码中的换行,不影响输出结果
例:
print("this is the \
same thing") #等同于print("this is th e same thing")
当有三个引号(''')或者(''' '''),可使用单、双引号,并可以直接换行:
print('''
"what's your name?"I asked.
"I'm Han.''
''')
用print输出以下文字:
1.
He said, "I'm yours!"
2.
\\_v_//
3.
Stay hungry,
stay foolish.
-- Steve Jobs
4.
*
***
*****
***
*
print('''He said,"I'm yours!"''')
print("\\\\_v_//")
print('''Stay hungry,
stay foolish.
--Steve Jobs ''')
print('*\n***\n*****\n***\n*')
print('''*
***
*****
***
*''')
二、字符串格式化
1、输出两个变量名,变量名之间用+表示,两个变量不换行输出:
str1='good'
str2='bye'
print(str1+str2)
也可以这样表示:
print('my age is '+str(18))
输出结果为
2、%d、%f、%s
num=18
print('My age is %d'%num) #%d会被%后面的值替换
整数%d
print('My age is %d'%18)
小数%f
print('Price is %f'%4.99)
保留两位小数%.2f、保留三位小数%.3f
print('Price is %.2f'%4.99)
print('Price is %.3f'%4.99)
字符串%s
print('Today is %s'%'Saturday')
3、元组tuple,基本数据结构
print("%s's score is %d"%('Mike',77)) #Mike's score is 77
('Mike',77)称为元组,中间用逗号隔开,还可以将里面值用变量名表示
name='Lily'
score=98
print("%s's score is %d"%(name,score)) #Lily's score is 98