1.字串的修飾
center
讓字串在指定的長度居中,如果不能居中左短右長,可以指定填充內容,預設以空格填充
ljust
讓字串在指定的長度左齊,可以指定填充內容,預設以空格填充
rjust
讓字串在指定的長度右齊,可以指定填充內容,預設以空格填充
zfill
將字串填充到指定長度,不足地方用0從左開始補充
format
按照順序,將後面的從引數傳遞給前面的大括號
strip
預設去除兩邊的空格,去除內容可以指定
rstrip
預設去除右邊的空格,去除內容可以指定
lstrip
預設去除左邊的空格,去除內容可以指定
練習:center():居中
test='hello'
print(test.center(9))
執行結果: hello #這個hello居中,預設由空格填充。效果不明顯,我們填充字元來檢視
test='hello'
print(test.center(9,'x'))
執行結果:xxhelloxx
練習:ljust():左對齊
test='hello'
print(test.ljust(9,'x'))
執行結果:hello***x
練習:rjust():右對齊
test='hello'
print(test.rjust(9,'x'))
執行結果:***xhello
練習:zfill()
test='hello'
print(test.zfill(9)) #不能指定字元填充,會報錯,預設0填充
執行結果:0000hello
練習:strip()、rstrip()、lstrip()
test=' hello ' #字串左右各加乙個空格
print(test.strip())
print(test.rstrip())
print(test.lstrip())
執行結果:
hello #去除兩邊空格
hello #去除右邊空格
hello #去除左邊空格
練習:format()
test="{} name is {}"
print(test.format('my','xiaoming'))
執行結果:my name is xiaoming
test="{} name is {}"
print(test.format('your','daming'))
執行結果:your name is daming
2.字串的變形
upper
將字串中所有的字母轉換為大寫
lower
將字串中所有的字母轉換為大寫
swapcase
將字串中所有的字母大小寫互換
title
將字串中單詞首字母大寫,單詞以非字母劃分
capitalize
只有字串的首字母大寫
expandtabs
將字串中的tab符號(『\t』)轉換為空格,tab符號(『\t』)預設的空格數是8,可以試下8,可以試下8,12
練習:upper()、lower()、swapcase()
print('hello'.upper())
print('hello'.lower())
print('hello'.swapcase())
執行結果:hello
hello
hello
練習:title()、capitalize ()
print('hello world'.title())
print('helloworld '.title())
執行結果:hello world
helloworld
print('hello world '.capitalize())
print('helloworld '.capitalize())
執行結果:hello world
helloworld
練習:
print('hello \t world '.expandtabs(10))
print('hello \t world '.expandtabs())
print('hello \t world '.expandtabs(4))
執行結果:hello world
hello world
hello world
字串變形
輸入描述 給定乙個字串s以及它的長度n 1 n 500 輸出描述 請返回變形後的字串。題目保證給定的字串均由大小寫字母和空格構成。輸入例子 this is a sample 16 輸出例子 sample a is this 需要考慮空格問題 include include include using...
字串變形詞
對於兩個字串a和b,如果a和b中出現的字元種類相同且每種字元出現的次數相同,則a和b互為變形詞,請設計乙個高效演算法,檢查兩給定串是否互為變形詞。解題思路 通過雜湊表將字串a放入map中,記錄出現的字母和次數,本題中使用陣列代替,key 陣列下標,value 陣列數值。public class tr...
字串的變形
這道題很多字串的邊界問題,涉及到空格,反轉的問題。很麻煩,記得以前只做過類似的題,應該有簡單的方法,但沒有找到,以後再看看。就像 hello world 一樣,然後我們要做的是把著個字串中由空格隔開的單詞反序,同時反轉每個字元的大小寫。比如 hello world 變形後就變成了 world hel...