字符串(2)

2018-02-24 15:48 更新

raw_input和print

自從本課程開始以來,我們還沒有感受到computer姑娘的智能。最簡單的智能應該體現在哪里呢?想想小孩子剛剛回說話的時候情景吧。

小孩學說話,是一個模仿的過程,孩子周圍的人怎么說,她(他)往往就是重復??垂倏梢酝涀约寒敵跏窃趺磳W說話了吧?就找個小孩子觀察一下吧。最好是自己的孩子。如果沒有,就要抓緊了。

通過python能不能實現這個簡單的功能呢?當然能,要不然python如何橫行天下呀。

不過在寫這個功能前,要了解兩個函數:raw_input和print

這兩個都是python的內建函數(built-in function)。關于python的內建函數,下面這個表格都列出來了。所謂內建函數,就是能夠在python中直接調用,不需要做其它的操作。

Built-in Functions


|abs() | divmod() | input()| open()| staticmethod()|

|all() | enumerate() | int() | ord() | str()|

|any() | eval() | isinstance()| pow()| sum()|

|basestring() | execfile() | issubclass() | print() | super()|

|bin() | file() | iter()| property()| tuple()|

|bool() | filter() | len() | range() | type()|

|bytearray() | float()| list() | raw_input()| unichr()|

|callable() | format() | locals() | reduce() | unicode()|

|chr() | frozenset() | long() | reload() | vars()|

|classmethod()| getattr()| map() | repr() | xrange()|

|cmp() | globals()| max()| reversed()| zip()|

|compile() |hasattr() | memoryview()| round() |?import()|

|complex() |hash() | min()| set() | apply()|

|delattr() |help()| next()| setattr()| buffer()|

|dict() | hex() |object() |slice() | coerce()|

|dir() | id() |oct() |sorted() |intern()|

這些內建函數,怎么才能知道哪個函數怎么用,是干什么用的呢?

不知道你是否還記得我在前面使用過的方法,這里再進行演示,這種方法是學習python的法寶。

>>> help(raw_input)

然后就出現:

Help on built-in function raw_input in module __builtin__:

raw_input(...)
    raw_input([prompt]) -> string

    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given,
    is printed without a trailing newline before reading.

從中是不是已經清晰地看到了raw_input()的使用方法了。

還有第二種方法,那就是到python的官方網站,查看內建函數的說明。https://docs.python.org/2/library/functions.html

其實,我上面那個表格,就是在這個網頁中抄過來的。

例如,對print()說明如下:

 print(*objects, sep=' ', end='\n', file=sys.stdout)

    Print objects to the stream file, separated by sep and followed by end. sep, end and file, if present, must be given as keyword arguments.

    All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

    The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Output buffering is determined by file. Use file.flush() to ensure, for instance, immediate appearance on a screen.

分別在交互模式下,將這個兩個函數操練一下。

>>> raw_input("input your name:")
input your name:python
'python'

輸入名字之后,就返回了輸入的內容。用一個變量可以獲得這個返回值。

>>> name = raw_input("input your name:")
input your name:python
>>> name
'python'
>>> type(name)
<type 'str'>

而且,返回的結果是str類型。如果輸入的是數字呢?

>>> age = raw_input("How old are you?")
How old are you?10
>>> age
'10'
>>> type(age)
<type 'str'>

返回的結果,仍然是str類型。

再試試print(),看前面對它的說明,是比較復雜的。沒關系,我們從簡單的開始。在交互模式下操作:

>>> print("hello, world")
hello, world
>>> a = "python"
>>> b = "good"
>>> print a
python
>>> print a,b
python good

比較簡單吧。當然,這是沒有搞太復雜了。

特別要提醒的是,print()默認是以\n結尾的,所以,會看到每個輸出語句之后,輸出內容后面自動帶上了\n,于是就換行了。

有了以上兩個準備,接下來就可以寫一個能夠“對話”的小程序了。

#!/usr/bin/env python
# coding=utf-8

name = raw_input("What is your name?")
age = raw_input("How old are you?")

print "Your name is:", name
print "You are " + age + " years old."

after_ten = int(age) + 10
print "You will be " + str(after_ten) + " years old after ten years."

對這段小程序中,有幾點說明

前面演示了print()的使用,除了打印一個字符串之外,還可以打印字符串拼接結果。

print "You are " + age + " years old."

注意,那個變量age必須是字符串,如最后的那個語句中:

print "You will be " + str(after_ten) + " years old after ten years."

這句話里面,有一個類型轉化,將原本是整數型after_ten轉化為了str類型。否則,就包括,不信,你可以試試。

同樣注意,在after_ten = int(age) + 10中,因為通過raw_input得到的是str類型,當age和10求和的時候,需要先用int()函數進行類型轉化,才能和后面的整數10相加。

這個小程序,是有點綜合的,基本上把已經學到的東西綜合運用了一次。請看官調試一下,如果沒有通過,仔細看報錯信息,你能夠從中獲得修改方向的信息。

原始字符串

所謂原始字符串,就是指字符串里面的每個字符都是原始含義,比如反斜杠,不會被看做轉義符。如果在一般字符串中,比如

>>> print "I like \npython"
I like 
python

這里的反斜杠就不是“反斜杠”的原始符號含義,而是和后面的n一起表示換行(轉義了)。當然,這似乎沒有什么太大影響,但有的時候,可能會出現問題,比如打印DOS路徑(DOS,有沒有搞錯,現在還有人用嗎?)

>>> dos = "c:\news"
>>> dos
'c:\news'        #這里貌似沒有什么問題
>>> print dos    #當用print來打印這個字符串的時候,就出問題了。
c:
ews

如何避免?用前面講過的轉義符可以解決:

>>> dos = "c:\\news"
>>> print dos
c:\news

此外,還有一種方法,如:

>>> dos = r"c:\news"
>>> print dos
c:\news
>>> print r"c:\news\python"
c:\news\python

狀如r"c:\news",由r開頭引起的字符串,就是原始字符串,在里面放任何字符都表示該字符的原始含義。

這種方法在做網站設置網站目錄結構的時候非常有用。使用了原始字符串,就不需要轉義了。

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號