python基礎實戰(二)-str

字符串

#python2的寫法
print('%s %s' % ('one','two'))
print('{} {}'.format('one','two'))
#python2的寫法,%d format: a number is required, not str,只能接收數字
print('%d %d' % (1,2))
# python3的寫法
print('{} {}'.format(1,2))
#可以調換輸入順序
print('{1} {0}'.format('one','two'))

//輸出結果
one two
one two
1 2
1 2
two one
a=5
b=10
print('Five plus ten is {a+b} and not {2*(a+b)}.')
# python3的表達法,將上述有賦值的參數計算出來
print(f'Five plus ten is {a+b} and not {2*(a+b)}.')

# 字符串需用雙引號
name='huohuo'
question='hello'
print(f"Hello,{name}! How's it {question}?")

//輸出結果
Five plus ten is {a+b} and not {2*(a+b)}.
Five plus ten is 15 and not 30.
Hello,huohuo! How's it hello?

字符串測試:
有兩個字符串a和b,按照abba的順序輸出
輸出 例如"Hi" 和 “Bye” returns “HiByeByeHi”.

a="Hi"
b="Bye"
print(a+b*2+a)
# 用加號不用逗號的原因,逗號是會有空格符的
print(a,b*2,a)

//輸出結果
HiByeByeHi
Hi ByeBye Hi

字符串截取,替換,查找位置

s='woshiyigehaoxuesheng'
# 訪問s裏邊第二個到第四個的元素(從0開始),包含第二個,但不包含第四個
s[2:4]
# 字符串右5位
s[-5:]
# 將字符串中的o元素都用9來替換
s=s.replace('o','9')
print(s)
# 在字符串str裏查找字符串的初始位置
s.find('xue')

//輸出結果
'sh'
'sheng'
w9shiyigeha9xuesheng
12

字符串通過固定符號轉集合

# 字符串分割列表
str='a,b,c,d'
strlist=str.split(',')
for value in strlist:
    print(value)

//輸出結果
a
b
c
d
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章