【Python入门】4、字符串,字符串格式化

一、字符串

字符串用双引号""或者单引号''表示,双引号里面可以只有单引号,单引号里面可以只有双引号

''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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值