Python-字符串

用单引号,双引号, 三引号创建字符串。

不同数据类型是不能够合并的,必须转换为同一类型

num = 1
string = '1'
num2 = int(string)
print(num + num2)

 

 

 

加号( + )用于字符串连接运算,星号( * )则用于字符串重复

words = 'words' * 3
print(words)
wordswordswords

 

索引:

name = 'My name is Mike'
print(name[0])

‘M’

print(name[-1])

‘e’

 

 

 

切片:

print(name[0:])

My name is Mike  #取所有值

 

print(name[0:-1])

My name is Mik  #从0位开始,到-1位之前的所有值

 

print(name[::-1])

ekiM si eman yM  #从右往左

 

a="123456"

print(a[1::2])

246  # 2 就是步长 意思是从索引为 1 的元素开始 每隔2个元素取一次元素

 

url = 'http://ww1.site.cn/14d2e8ejw1exjogbxdxhj20ci0kuwex.jpg'
file_name = url[-10:]
print(file_name)

0kuwex.jpg

 

 

字符串方法:

replace:

phone_number = '1386-666-0006'
hiding_number = phone_number.replace(phone_number[:9],'*'*9)  #phone_number[:9]代表被替换掉的部分
print(hiding_number)  

*********0006

 

format:  #Python的字符串格式化有两种方式: 百分号方式、format方式

city = input("write down the name of city:")
url = "http://apistore.baidu.com/microservice/weather?citypinyin={}".format(city)

 

 

 

print('{0} a word she can get what she {1} for.'.format('With','came')) 

 

posted @ 2023-01-09 11:15  昵称不重要!  阅读(36)  评论(0)    收藏  举报