1. 程式人生 > >Python基礎入門(字串)

Python基礎入門(字串)

#字串   單引號和雙引號都一樣
str1 = "abc"
str2 = 'abc'
#多行字串用三引號
str3 = '''a
b
c
'''
print(str1,str2,str3)
abc abc a
b
c

In [4]:

#轉義字元 \
print("\\")
print("/")
\
/
In [28]:

#序列通用功能
print('a' in 'abc')
print('a'+'b')
print('a'*4)
str1 = 'abcdefg'
print(str1[0:-1:2])
​
#upper 變成大寫  lower變成小寫
str2 = str1.upper()
str3 = str2.lower()
​
#大小寫呼喚 swapcase
str3.swapcase()
#首字母大寫 capitalize() 
str3.capitalize()
​
#isnumeric()如果字串只包含數字就返回True,否則只返回False
str4 = "123abc"
str5 = "123456"
print(str4.isnumeric())
print(str5.isnumeric())
​
# isalpha 如果字串至少有一個字元並且所有字元都是字母則返回True,否則返回False
str6 = "abcdef"
print(str6.isalpha())
print(str5.isalpha())
​
#刪除字串末尾的空格 rstrip()
str7 = "abc    "
print(str7)
str7.rstrip()
True
ab
aaaa
ace
False
True
True
False
abc    
Out[28]:
7
In [49]:

#格式化字串
i = 20
print("he is the %d year`s old %s" % (i,'boy'))
he is the 20 year`s old boy
In [54]:

a= eval("[1,2,3]")
eval('print("abc")')
print(a)
abc
[1, 2, 3]
In [128]:

#小作業
str = '''\
i am a boy
i am a girl\
'''
print(str)
​
local = "D:/kobe.jpeg"
​
#print(33+"22") error
print(33+int("22"))
#print("33"+str(22)) error
​
# .split()用於拆分字串   join連線字串
m = 'a,b,c'
n = m.split(',')
w = '_'.join(m)
print(m,n,w)
​
#替換
str10 ="i am a ... ...  "
str10 = str10.replace('...','handsome',1)
str10.replace('...','boy',1)
​
#print(str10.replace(...,handsome))
i am a boy
i am a girl
55
a,b,c ['a', 'b', 'c'] a_,_b_,_c
Out[128]:
'i am a handsome boy  '