日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

字符串(string)的常用语法和常用函数

發布時間:2023/12/1 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 字符串(string)的常用语法和常用函数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在python中,加了引號(單引號、雙引號、三引號)的字符就是字符串類型,python并沒有字符類型。

字符串也是很常用的數據類型,這里介紹一些用的較多的語法和方法,直接以代碼示例展示。

1 str = 'helloworld' 2 str1 = 'i' 3 str2 = 'love' 4 str3 = 'you' 5 print(str) 6 print(str[:]) 7 print(str[2:]) # 字符串下標是從0開始記,所以下標2對應hello的第一個l 8 print(str[:5]) # 會截取從0位到(5-1)位 9 print(str[3:8]) # 下標3對應hello的第二個l,而后一位數對應(8-1)位是r 10 print(str[-2:])    # 索引可以是負數,意味著從后往前數 11 print(str1 + " " + str2 + " " + str3) # 字符串拼接 12 print(str3*5) # 相當于字符串的快速復制

輸出結果:

1 helloworld 2 helloworld 3 lloworld 4 hello 5 lowor 6 ld 7 i love you 8 youyouyouyouyou

?

常用的方法:

1 str = 'helloword' 2 str1 = 'HELLOWORD' 3 str2 = 'HelLOwoRd' 4 5 6 print(str.title()) 7 print(str1.title()) # string.title()函數讓字符串首字母大寫,其他都小寫 8 9 print(str.upper()) 10 print(str2.upper()) # string.upper()函數使字符串所有字母大寫 11 12 print(str1.lower()) 13 print(str2.lower()) # string.lower()函數使字符串所有字母小寫

輸出結果:

1 Helloword 2 Helloword 3 HELLOWORD 4 HELLOWORD 5 helloword 6 helloword

?

去除字符串前后的空格:

1 str3 = ' hello' 2 str4 = 'hello ' 3 str5 = ' hello ' 4 str6 = "hello word" 5 6 print(str3, end=" ") 7 print(str4, end=" ") 8 print(str5) # 顯示各自輸出字符串,為了方便觀察,讓三個字符串輸出在一行 9 print(str3.lstrip(), end="") # 去除字符串左邊或前邊的空格 10 print(str4.rstrip()) # 去除字符串右邊或后邊的空格 11 print(str5.strip(), end="") # 去除字符串前后的空格 12 print(str3.strip()) # 不能去除字符串中間的空格,因為這種空格也屬于字符串本身內容的一部分 13 print(str6.strip())

?

輸出結果:

hello hello hello hellohello hellohello hello word

?

關于字符串的使用方法還有很多,剛開始學時也不可能都去學,只能是先學一些常用的,然后在以后的深入學習中遇到了再去學,或者需要了再去學。

?

?

轉載于:https://www.cnblogs.com/zuoxide/p/10509905.html

總結

以上是生活随笔為你收集整理的字符串(string)的常用语法和常用函数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。