Python语言学习之字符串那些事:python和字符串的使用方法之详细攻略
生活随笔
收集整理的這篇文章主要介紹了
Python语言学习之字符串那些事:python和字符串的使用方法之详细攻略
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python語言學習之字符串那些事:python和字符串的使用方法之詳細攻略
?
?
?
?
目錄
python與字符串的那些事
1、字符串中只保留漢字
2、字符串的截取
3、在字符串中加入變量
4、字符串與列表轉換
5、判判斷字符串是否為空
?
?
?
?
?
?
python與字符串的那些事
1、字符串中只保留漢字
import re str = "hello,world!!%[545]你好234世.界。。。" str = re.sub("[A-Za-z0-9\!\%\[\]\,\。\.]", "", str) print(str) #你好世界?
2、字符串的截取
str ='0123456789' print(str[:]) #截取字符串的全部字符,可以截取出所有數字,即變為數值類型 print(str[2]) #截取第3個字符 print(str[0:3]) #截取第1位~第3位的字符print(str[6:]) #截取第7個 ~ 結尾 print(str[:-3]) #截取從第1位~倒數第3個字符之前 print(str[-1]) #截取倒數第1個字符 print(str[-3:-1]) #截取倒數第3位~倒數第1位之前的字符 print(str[-3:]) #截取倒數第3位 ~ 結尾 print(str[:-5:-3]) #逆序截取 print(str[::-1]) #創造一個與原字符串順序相反的字符串?
3、在字符串中加入變量
#在字符串中加入變量 #T1 +法 name = 'Jason' print('my name is '+name) #T2 采用%s、%d、%f等符號 name = 'Jason' age = 26.26 price = 31415.926 print('My name is %s'% (name)) print('I am %d'% (age)+' years old') #%d,保留整數 print('My price is %f'% (price)) #%f,保留指定位數小數(四舍五入) # My name is Jason # I am 26 years old # My price is 31415.926000 sql_command1="ALTER TABLE %s \n DROP COLUMN %s" ?%(table_name, COLUMN_name) #字符串中加入多個變量 #T3 format函數,變量較多的情況,加入加'+'或者'%'相對比較麻煩,這種情況下可以使用format函數 info = 'My name is {my_name},I am {my_age} years old,my price is {my_price}'\.format(my_name=name, my_age=age, my_price=price) print(info)?
4、字符串與列表轉換
#python字符串與列表的相互轉換 1、字符串轉列表 str1 = "hi hello world" print(str1.split(" ")) # 輸出 ['hi', 'hello', 'world']2、列表轉字符串 l = ["hi","hello","world"] print(" ".join(l)) # 輸出:hi hello world?
?
5、判判斷字符串是否為空
if str.strip()=='':print('str,該字符串為空!') else:print('str,該字符串非空!')?
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的Python语言学习之字符串那些事:python和字符串的使用方法之详细攻略的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python语言学习之时间那些事:pyt
- 下一篇: Python语言学习之文件夹那些事:py