Python 学习笔记(七)Python字符串(一)

字符串

字符串或串(String)是由数字、字母、下划线组成的一串字符,用双引号或单引号包裹的为字符串

1 >>> "hello world"
2 'hello world'
3 >>> 'hello world'
4 'hello world'
5 >>> "250"
6 '250'
7 >>> type("200")
8 <type 'str'>

   下面示例:

  语法错误 第一行出现三个单引号,Python 解析器匹配不上成对的引号,所以报错。

  解决方法:1、可使用双引号包裹 2、可以使用反斜杠\ 转义字符

 1 >>> 'What's your name?'
 2   File "<stdin>", line 1
 3     'What's your name?'
 4           ^
 5 SyntaxError: invalid syntax
 6 >>> "What's your name?"
 7 "What's your name?"
 8 >>> 'What\'s your name?'
 9 "What's your name?"
10 >>>

  字符串 、数字互转

  内置函数int()  str() float()

 1 >>> a = int("200")
 2 >>> a
 3 200
 4 >>> type(a)
 5 <type 'int'>
 6 >>> b = str(200)
 7 >>> type(b)
 8 <type 'str'>
 9 >>> c = float("200.5") 10 >>> type(c) 11 <type 'float'> 12 >>>

  转义符

 第5行出现 \n 换行

 解决方法:使用反斜杠\ 或者在原始字符串前+r ,会显示原始字符串

1 >>> print "c:\\news"
2 c:\news
3 >>> print r"c:\news"
4 c:\news
5 >>> print "c:\news"
6 c:
7 ews

字符串相加

 字符串相加是将两个字符串拼接在一起

 1 >>> "3" + "6"
 2 '36'
 3 >>> "py" + "thon"
 4 'python'
 5 >>> 8 + "6"
 6 Traceback (most recent call last):
 7   File "<stdin>", line 1, in <module>
 8 TypeError: unsupported operand type(s) for +: 'int' and 'str'  不支持 int 和字符串相加,我们可以将其转换
 9 >>> 8 + int("6")
10 14
11 >>> str("8")+ "6"
12 '86'

 

转载于:https://www.cnblogs.com/wangruihua-521/p/8544554.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值