一、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-hk/n/182259.html