python string

一、封闭在单引号或双引号里

 

print('spam eggs')
print('doesn\'t')# use \' to escape the single quote 
print("doesn't")# ...or use double quotes instead
print('"Yes," he said.')
print( "\"Yes,\" he said.")
print('"Isn\'t," she said.')
print('"Isn\"t," she said.')

spam eggs
doesn't
doesn't
"Yes," he said.
"Yes," he said.
"Isn't," she said.
"Isn"t," she said.


二、  处理\n引起的换行

print('C:\some\name')
print('C:\some\\name')
print(r'C:\some\name')


C:\some
ame
C:\some\name
C:\some\name


三、 占据多行的string,如何输出

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")#单引号'''...... ''',双引号都行""".......""" , \是一行写不下的时候,连接这一行与下一行


Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to


四、string的连接

print('py' 'thon' '11')#这种只能是常量的连接
print('ab', 'cd')#这种不是连接
print(3*'un' + 'ium')
print(3*'un' 'ium')
print(3*'un', 'ium')

prefix = 'py'
print(prefix + 'ttt')#变量与常量的连接,只能这种

text = ('Put several strings within parentheses '
            'to have them joined together.')
print(text)

python11
ab cd
unununium
uniumuniumunium
ununun ium
pyttt
Put several strings within parentheses to have them joined together.


五、string的索引与切片

word = 'Python'
print(word[0])
print(word[-3])
print(word[:2])
#word[42] 越界,出错
print(word[4:42])
print(word[42:])#空字符串,即 ''
'''word[0] = 'J'
word[2:] = 'py' 
TypeError: 'str' object does not support item assignment
'''

P
h
Py
on


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值