python基礎文法

來源:互聯網
上載者:User

標籤:happy   空白   修改   last   message   python   函數名   blog   tin   

1、變數的命名規則

  • 變數名只能包含字母、數字和底線。變數名可以字母或底線打頭,但不能以數字打頭,例如,可將變數命名為message_1,但不能將其命名為1_message。
  • 變數名不能包含空格,但可使用底線來分隔其中的單詞。例如,變數名greeting_message可行,但變數名greeting message會引發錯誤。
  • 不要將Python關鍵字和函數名用作變數名,即不要使用Python保留用於特殊用途的單詞,如print (請參見附錄A.4)。
  • 變數名應既簡短又具有描述性。例如,name比n好,student_name比s_n好,name_length比length_of_persons_name好。
  • 慎用小寫字母l和大寫字母O,因為它們可能被人錯看成數字1和0。

2、字串:就是一系列字元。在Python中,用引號括起的都是字串,其中的引號可以是單引號,也可以是雙引號。

‘Hello python world!‘"The language ‘Python‘ is named after Monty Python, not the snake."

3、使用方法修改字串的大小寫。

  1. title() 以首字母大寫的方式顯示每個單詞,即將每個單詞的首字母都改為大寫。
  2. upper()每個單詞都改為大寫。
  3. lower()每個單詞都改為小寫。
name = ‘tom frank‘print(name.title())
print(name.upper())
print(name.lower())輸出結果:Tom Frank
TOM FRANK
tom frank

4、合并拼接字串

first_name = ‘tom‘last_naem = ‘frank‘full_name = first_name + ‘ ‘ + last_nameprint(full_name)print("Hello, " + full_name.title() + "!")

5、使用定位字元或換行添加空白

  • 使用字元組合\t,添加定位字元
  • 使用字元組合\N,換行
print("Languages:\n\tPython\n\tC\n\tJava")輸出結果:Languages:    Python    C    Java

6、刪除空白

  1. 使用rstrip(),刪除末尾空白
    favorite_languages = ‘Python ‘
    #輸出原值
    print(favprite_langes)
    #去掉末尾空白,臨時性
    print(favorit_languages.rstrip())
    #永久去掉末尾空白
    favorite_languages = favorite_languages.rstrip()
    print(favorite_languages)
  2. 使用lstrip(),刪除開頭空白
    favorite_languages = ‘ Python‘#輸出原值print(favorite_languages)#去掉開頭空白,臨時性print(favorite_languages.lstrip())#永久性去掉開頭空白favorite_languages = favorite_languages.lstrip()print(favorite_languages)
  3. 使用strip(),刪除兩端空白
    favoriet_languages = ‘ Pyrhon ‘#輸出原值print(favorite_languages)#去掉兩端空白print(favorite_languages.strip())

7、使用函數str(),避免類型錯誤

age =  24message = "Happy " +  str(age) + "rd Birthday!"print(message)

 

python基礎文法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.