我是靠谱客的博主 冷酷花瓣,这篇文章主要介绍简单讲解Python中的字符串与字符串的输入输出,现在分享给大家,希望可以做个参考。

字符串
字符串用''或者""括起来,如果字符串内部有‘或者",需要使用\进行转义

复制代码
1
2
>>> print 'I\'m ok.' I'm ok.

转义字符\可以转义很多字符,比如\n表示换行,\t表示制表符,字符\本身也要转义,所以\\表示的字符就是\。当然如果不需要转义,可以使用r'':

复制代码
1
2
3
4
>>> print '\\\t\\' \ \ >>> print r'\\\t\\' \\\t\\

如果字符串内部有很多换行,用\n写在一行里不好阅读,为了简化,Python允许用'''…'''的格式表示多行内容:

复制代码
1
2
3
4
5
6
>>> print '''line1 ... line2 ... line3''' line1 line2 line3

如果写成程序,就是:

复制代码
1
2
3
print '''line1 line2 line3'''


可能出现的问题
中文编码问题

复制代码
1
# coding = utf-8

结果报错:

复制代码
1
SyntaxError: Non-ASCII character ‘/xe6'

所以最后改成了

复制代码
1
# coding=utf-8

唉....

Unicode编码问题

复制代码
1
2
3
4
5
6
7
8
Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> len('中文') 6 >>> len(u'中文') 2 >>>

注意: 这个问题是由python编码导致的,详细的编码问题详见字符串和编码,但是在python 3.x中这个编码问题就不存在了:

复制代码
1
2
3
4
5
6
7
8
Python 3.4.0 (default, Jun 19 2015, 14:20:21) [GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> len('中文') 2 >>> len(u'中文') 2 >>>
 

输出

复制代码
1
2
3
4
5
6
7
8
>>> print 'hello, world' hello, world >>> print 'The quick brown fox', 'jumps over', 'the lazy dog' The quick brown fox jumps over the lazy dog >>> print '100 + 200 =', 100 + 200 100 + 200 = 300

输入

复制代码
1
2
3
4
5
6
7
8
9
10
11
>>> name = raw_input() Michael >>> name 'Michael' >>> print name Michael >>> name = raw_input('please enter your name: ') please enter your name:

注意: raw_input返回的永远是字符串,也就是说你输入一个int型,返回的是一个数字字符串,你需要进行转换:

复制代码
1
2
3
4
5
6
7
8
>>> number = raw_input("输入一个整数:") 输入一个整数:123 >>> number '123' >>> number = int(raw_input("输入一个整数:")) 输入一个整数:123 >>> number 123

最后

以上就是冷酷花瓣最近收集整理的关于简单讲解Python中的字符串与字符串的输入输出的全部内容,更多相关简单讲解Python中内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(154)

评论列表共有 0 条评论

立即
投稿
返回
顶部