字符串是 Python 中最常用的數據類型。我們可以使用引號('或")來創建字符串。
創建字符串很簡單,只要爲變量分配一個值即可。例如:
#!/usr/bin/env python
#字符串的基本操作
name='Hello'
name1='Python'
以下是對python中常用的一些字符創操作整理。如有不全請包涵!
#!/usr/bin/env python #字符串的基本操作 name='Hello' name1='Python' #+加號 用來連接字符串 print (name + name1)#運行結果爲HelloPython #* 乘號,用來重複字符創 print(name*2) # 運行結果爲:HelloHello #[] 中括號根據索引(也就是位置一般跟列表是都是從0開始) print (name[0])#如果是0的話打印出來的就是H,如果是1 就是e #【:】截取字符創的一部分:如【0:3】 print (name[0:3]) #運行結果爲:hel #in 代表一個字符是存在該字符串中時返回true if 'H' in name: print ('H 在 name 變量中') #not in 如果一個字符不存在該字符串中返回true if 'y' not in name: print ('y 不存在變量name中') #python對於字符串的內建常用操作方法 #center 指定一個以python居中寬度爲50的字符串,- 爲填充符號。 print ('python'.center(30,'-'))#運行結果爲:------------python------------ #count 統計'l' 在hello這個字符創裏出現過幾次 print ('hello'.count('l')) #endswith 判斷字符串是否以'lo'結尾,是的話返回個true值 print ('hello'.endswith('lo')) #startswith 判斷字符串是否以 'he' 開頭,是的話返回個true值 print ('hello'.startswith('he')) #index 查找 h 在字符串中的索引也就是位置。 print ('python'.index('h'))#運行結果是 h 在python字符串中的索引位置是 3 #find 查找 y 在字符串中的位置,等同於index ,不過find如果不在字符串中會返回一個-1的值 print ('python'.find ('y')) #strip 消除空格 one = input ('請輸入一個字符處:') if one.strip() == 'wang': print ('你輸入的正確')#運行結果 是輸入wang這個字符串時如果跟着空格,也會識別爲正確,如果沒有strip這個參數時輸入wang 帶空格就會報錯 #isdigit() 判斷您輸入的是否是純數字,是數字則返回true two = input ('請輸入數字:') '123'.isdigit() if two.isdigit(): print ('你輸入的是數字') else: print('請輸入純數字') #.isalnum() 判斷輸入的內容是否包含特殊字符,無特殊字符則返回true str=input('請輸入您的內容: ') if str.isalnum(): print ('輸入正確') else: print ('請不要輸入特殊字符')