一、Python string函數用法
在Python中,字元串是指由一系列字元組成的序列,Python string函數用於處理字元串類型。
Python string函數包括以下用法:
string.capitalize() # 把字元串的第一個字元大寫
string.casefold() # 把字元串全部轉換為小寫
string.center(width[, fillchar]) # 返回一個指定寬度的字元串,原字元串居中,用指定字元或空格填充
string.count(sub[, start[, end]]) # 返回字元串中包含子字元串的個數
以string.capitalize()為例進行演示:
# 先定義一個字元串
str = "hello world!"
# 輸出結果為:Hello world!
print(str.capitalize())
該代碼會輸出”Hello world!”,因為string.capitalize()會把字元串的第一個字元大寫。
二、Python print函數
Python中的print函數用於輸出信息到控制台。
使用Python print函數將結果輸出:
str1 = "hello"
str2 = "world"
# 輸出結果為:hello world
print(str1, str2)
使用Python print函數強制換行:
str = "hello world!"
# 輸出結果為
# hello
# world!
print(str, end="\n\n")
其中,end="\n\n"
表示輸出後換兩個新行。
三、Python的string函數
Python string函數還包括以下用法:
string.encode(encoding='UTF-8',errors='strict') # 將字元串轉換為指定編碼;
string.endswith(suffix[, start[, end]]) # 測試字元串是否以指定的後綴結尾,返回 True 或 False;
string.expandtabs(tabsize=8) # 把字元串中的 tab 符號 (\t) 轉換為空格,tabsize 指定轉換的空格數,默認為 8;
string.find(sub[, start[, end]]) # 搜索字元串中指定的子字元串並返回起始索引,如果沒有匹配返回 -1;
以string.encode()為例進行演示:
str = "Python, 真是個不錯的編程語言!"
# 輸出結果為:b'Python, \\xe7\\x9c\\x9f\\xe6\\x98\\xaf\\xe4\\xb8\\xaa\\xe4\\xb8\\x8d\\xe9\\x94\\x99\\xe7\\x9a\\x84\\xe7\\xbc\\x96\\xe7\\xa8\\x8b\\xe8\\xaf\\xad\\xe8\\xa8\\x80!'
print(str.encode())
四、Python函數大全及使用
Python提供了大量的函數,在這裡我們僅列舉其中幾個常用的函數:
int(x [,base]) # 將一個字元串/數字/浮點數轉換為整數;
title() # 返回 "標題化" 的字元串,就是說所有單詞都是以大寫開始,其餘字母均小寫;
isdigit() # 如果字元串只包含數字,則返回 True,否則返回 False;
以int()函數為例進行演示:
str = "123456"
# 輸出結果為:123456
print(int(str))
五、Python字元串函數
Python字元串函數還包括以下用法:
string.lstrip() # 返回去掉左側空格的字元串;
string.join(sequence) # 連接序列中的元素以構造一個新的字元串;
string.partition(sub) # 查找子字元串,返回一個3元組,包含第一個出現位置之前的字元、子字元串、第一個出現位置之後的字元;
string.replace(old, new[, count]) # 返回一個字元串,在這個字元串中將字元串old替換為new,如果指定第3個參數則替換不超過count次。
以string.lstrip()為例進行演示:
str = " hello world!"
# 輸出結果為:hello world!
print(str.lstrip())
六、Python count函數
Python count函數用於返回字元串中指定子串出現的次數。
示例代碼:
str = "this is a dog"
# 輸出結果為:1
print(str.count("dog"))
七、Python函數int
Python函數int接受數字字元串並將其轉換為整數。
示例代碼:
str = "123"
# 輸出結果為:123
print(int(str))
八、Python函數title
Python函數title用於將所有單詞的首字母大寫。
示例代碼:
str = "this is a dog"
# 輸出結果為:This Is A Dog
print(str.title())
九、Python的string函數
Python的string函數還包括以下用法:
string.strip([chars]) # 在字元串的開頭和結尾刪除空白字元(包括換行符、製表符等);
string.swapcase() # 返回大小寫字母互換後的字元串;
string.startswith(obj, beg=0,end=len(string)) # 檢查字元串是否是以obj開始,是的話返回 True,否則返回 False;
string.upper() # 將字元串中的小寫字母轉換為大寫字母;
以string.strip()為例進行演示:
str=" hello world! "
# 輸出結果為:hello world!
print(str.strip())
總結
本文詳細介紹了Python字元串函數的用法,涉及Python的string函數、print函數、count函數、title函數等,希望對初學者有所幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/182259.html