字符串输入python用到的输入一般有两种方式,input() 和 raw_input() ,区别是,前者只能输入数字,后者输入的是字符串,使用如下:
in [226]: help(input)
help on built-in function input in module __builtin__:
input(...)
input([prompt]) -> value
equivalent to eval(raw_input(prompt)).
in [228]: input()
d
---------------------------------------------------------------------------
nameerror traceback (most recent call last)
<ipython-input-228-25ede6ea20bf> in <module>()
----> 1 input()
<string> in <module>()
nameerror: name 'd' is not defined
in [229]: input()
23
out[229]: 23
in [230]: input(input a num)
input a num444
out[230]: 444
in [231]: n = input()
23
in [232]: n
out[232]: 23
in [233]: s = raw_input(input sth.: )
input sth.: 123
in [234]: s
out[234]: '123'
in [235]: s = raw_input(input sth.: )
input sth.: sss
in [236]: s
out[236]: 'sss'
字符串输出输出使用print即可,后边可加变量,也可以直接用、'和'''来包含字符串,使用示例如下:
正常情况下均可以使用,可以使用一种包含一个字符串,字符串中可以包含另外一种(但是不可以包含同一种,否则需要转义)
in [241]: print i'm tom
i'm tom
in [242]: print 'abc'
abc
in [243]: print abc
abc
in [244]: print '''abc'''
abc
in [245]: print 'hhh'
hhh
in [246]: print 'hello world'
'hello world'
in [247]: print 'i'am bt'
file <ipython-input-247-efa01090d6c6>, line 1
print 'i'am bt'
^
syntaxerror: invalid syntax
# 字符串转义
in [248]: print 'i\'m bt'
i'm bt
in [249]: print ''' i'm tom, hhhe'''
i'm tom, hhhe
换行
in [250]: print ''' i
.....: am tom
.....: hhha '''
i
am tom
hhha
in [254]: print 'i am \
.....: tom \
.....: hh'
i am tom hh
in [255]: print i\
.....: am \n \
.....: tom \n
iam
tom
# 此处有空行
# 输出非转义字符串
in [256]: print ri\'m tom
i\'m tom
数字字符串转换直接使用str()或者int()即可,没什么可说的,如下:
in [256]: print ri\'m tom
i\'m tom
in [257]: n = raw_input()
123
in [258]: n
out[258]: '123'
in [259]: n = int(n)
in [260]: n
out[260]: 123
in [261]: str(n)
out[261]: '123'
以上就是python字符串输入输出的详细介绍的详细内容。