python string

来源:互联网 发布:新疆商务厅 数据分析 编辑:程序博客网 时间:2024/05/22 06:47

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

 

print('spam eggs')print('doesn\'t')# use \' to escape the single quote print("doesn't")# ...or use double quotes insteadprint('"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
原创粉丝点击