字串下常用的工具

2021-10-04 23:10:22 字數 2973 閱讀 6033

text = "love"

text = text.capitalize()

print(text)

輸出:love

text = "love"

text = text.lower()

print(text)

輸出:love

text = "abcdefg"

text = text.lower()

print(text)

輸出:abcdefg

text = "love"

text = text.center(10,"*")

print(text)

輸出:***love***

text = "love"

text = text.ljust(10,"*")

print(text)

輸出:love******

text = "love"

text = text.rjust(10,"*")

print(text)

輸出:******love

text = "lovelovelove"

text = text.count("o")

print(text)

輸出:3

text = "love"

text = text.endswith("o")

print(text)

輸出:false

text = "lovelove"

text = text.find("e")

print(text)

輸出:3    #返回的是下標(索引)

text = "i am , my age is "

text = text.format(name = "jhon", age = 18)

print(text)

輸出:i am jhon, my age is 18

text = "i am , my age is "

text = text.format("jhon",18)

print(text)

輸出:i am jhon, my age is 18

text = "name\temail\tphone"

text = text.expandtabs(8)

print(text)

輸出:name email phone

text = "ilove39234__!"

text = text.isalnum()

print(text)

輸出:false

text = "i love python" 

text.title()

print(text)

輸出:i love python

1 text = "我是乙隻兔子"

2 t = "_"

3 text = t.join(text)

4 print(text)

輸出 :我_是_一_只_兔_子

1 text = "    ldfiej  es  \t"

2 text = text.strip()

3 print(text)

#去除首位空白字元

輸出 :flejli  es

1 text = "abcdefgh"

2 text = text.partition("d")

3 print(text)

輸出:('abc', 'd', 'efgh')

text = "abcdabcdabcd"

text.split("c")

['ab', 'dab', 'dab', 'd']

text = "abcd\nab\ncd\tabc\ndab"

text.splitlines(false)

輸出:['abcd', 'ab', 'cd\tabc', 'dab']

text = "abcd\nab\ncd\tabc\ndab"

text.splitlines(true)

['abcd\n', 'ab\n', 'cd\tabc\n', 'dab']

a = "abcdabcdabcd"

a.replace("ab","12")

輸出:'12cd12cd12cd'

test = "python3" 

t1 = test[0] #取單個字元

t2 = test[0:2] #取乙個範圍內 0=< <2

t3 = test[0:-1] #-1代表最後一位

t4 = test[:3] # : 冒號前面不寫預設為0

t5 = test[0:] # : 冒號後面不寫預設為結尾

print("t1 = ",t1)

print("t2 = ",t2)

print("t3 = ",t3)

print("t4 = ",t4)

print("t5 = ",t5)

結果分別為:

t1 = p

t2 = py

t3 = python

t4 = pyt

t5 = python3

字串工具類

字串工具類 author administrator public class djystringutils 判斷字串是否不為空 param str 字串 return 是否不為空 public static boolean isnotempty string str 截斷字串兩側的逗號 param...

字串工具 StrUtil(hutool)

依賴包 dependency groupid cn.hutool groupid artifactid hutool all artifactid version 5.5.7 version dependency 原始碼舉例 import cn.hutool.core.util.strutil im...

常用字串處理工具

1 字串判斷 檢查字串是否是空白 stringutil.isblank null true stringutil.isblank true stringutil.isblank true stringutil.isblank bob false stringutil.isblank bob fals...