码迷,mamicode.com
首页 > 编程语言 > 详细

Python基础(二)之数据类型和运算(2)——字符串

时间:2017-12-31 13:37:07      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:连续字符串   引号   eth   cape   pre   color   数据类型   name   inf   

字符串基础

Python 也提供了可以通过几种不同方式表示的字符串。它们可以用单引号 (‘...‘) 或双引号 ("...") 标识 \ 可以用来转义引号: 

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

 在交互式解释器中,输出的字符串会用引号引起来,特殊字符会用反斜杠转义。虽然可能和输入看上去不太一样,但是两个字符串是相等的。如果字符串中只有单引号而没有双引号,就用双引号引用,否则用单引号引用。print() 函数生成可读性更好的输出, 它会省去引号并且打印出转义后的特殊字符:

>>> "Isn\‘t," she said.
"Isn\‘t," she said.
>>> print("Isn\‘t," she said.)
"Isn‘t," she said.
>>> s = First line.\nSecond line.  # \n means newline
>>> s  # without print(), \n is included in the output
First line.\nSecond line.
>>> print(s)  # with print(), \n produces a new line
First line.
Second line.

如果你前面带有 \ 的字符被当作特殊字符,你可以使用 原始字符串,方法是在第一个引号前面加上一个 r:

>>> print(C:\some\name)  # here \n means newline!
C:\some
ame
>>> print(rC:\some\name)  # note the r before the quote
C:\some\name

 

 字符串多行输出

 字符串文本能够分成多行。一种方法是使用三引号:"""...""" 或者 ‘‘‘...‘‘‘。行尾换行符会被自动包含到字符串中,但是可以在行尾加上 \ 来避免这个行为。下面的示例: 可以使用反斜杠为行结尾的连续字符串,它表示下一行在逻辑上是本行的后续内容:

1 print("""2 Usage: thingy [OPTIONS]
3      -h                        Display this usage message
4      -H hostname               Hostname to connect to
5 """)

将生成以下输出(注意,没有开始的第一行):

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

 

 

 字符串格式化输出

万恶的字符串拼接
  python中的字符串在C语言中体现为是一个字符数组,每次创建字符串时候需要在内存中开辟一块连续的空,并且一旦需要修改字符串的话,就需要再次开辟空间,万恶的+号每出现一次就会在内从中重新开辟一块空间。

字符串可以由 + 操作符连接(粘到一起),可以由 * 表示重复:

>>> # 3 times ‘un‘, followed by ‘ium‘
>>> 3 * un + ium
unununium

相邻的两个字符串文本自动连接在一起。:

>>> Py thon
Python

它只用于两个字符串文本,不能用于字符串表达式:

>>> prefix = Py
>>> prefix thon  # can‘t concatenate a variable and a string literal
  ...
SyntaxError: invalid syntax
>>> (un * 3) ium
  ...
SyntaxError: invalid syntax

如果你想连接多个变量或者连接一个变量和一个字符串文本,使用 +:

>>> prefix + thon
Python

这个功能在你想切分很长的字符串的时候特别有用:

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

 

字符串拼接格式化输出

name = input("name:")
age = input("age:")
job = input("job:")

print("""
-------------info-----------
name:"""+name+"""
age:"""+age+"""
job:"""+job)

输入

name:Brain
age:23
job:IT

输出

-------------info-----------
name:Brain
age:23
job:IT

 

Python基础(二)之数据类型和运算(2)——字符串

标签:连续字符串   引号   eth   cape   pre   color   数据类型   name   inf   

原文地址:https://www.cnblogs.com/yz9110/p/8157417.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!