1. 程式人生 > >Python變數與字串

Python變數與字串

# 開啟檔案,寫入字串
file = open('/D/file.txt','w')
file.write('hello world!')

# 字串組合輸出
a = 'plays '
b = 'guitar '
c = 'Mr.Charles.'
d = c + a + b
print(d)

# 數字轉字元型別進行輸出
num = 1
string = '1'
num2 = int(string)
print(num + num2)

# 字串*數字1:
words = 'words' * 3
print(words)

# 字串*數字2:
word = 'a loooooong word'
num  = 12
string  = 'bang!'
total = string * (len(word) - num)
print(total)

# 字串用下標進行輸出
name = 'My name is Charles'
print(name[0])
'M'
print(name[-4])
'r'
print(name[11:14])
'Cha'
print(name[11:15])
'Char'
print(name[5:])
'me is Chrales'
print(name[:5])
'My na'

# 字串下標的組合輸出
word = 'friends'
find = word[0] + word[2:4] + word[-3:-1]
print(find)

# 爬取檔案命名(字串下標)
url = 'http://ww1.site.cn/14d2e8ejw1exjogbxdxhj20ci0kuwex.jpg'
file_name = url[-10:]

print(file_name)

# 字串replace函式,用*代替對應位置字元
number = '1777-917-7829'
hnumber = number.replace(number[:9],'*'* 9 )
print(hnumber)


# 查詢字串中的子串
search = '168'
num_a = '1398-168-0006'
num_b = '1681-222-0006'
print(search + ' is at ' + str(num_a.find(search)) + ' to ' + str(num_a.find(search) + len(search) - 1) + ' of num_a')

# 字串format函式用法(填空)
print('{} name is {}.'.format('My','Charles'))