Python学习第四天之字符串的拼接方式

柳三千

图片.png

字符串的拼接方式

s1='hello'
s2='world'
#(1)使用+号拼接
print(s1+s2)  #helloworld

#(2)使用字符串的join()方法
print(''.join([s1,s2]))#helloworld
print('.'.join(['172','253','18','251']))#172.253.18.251
print('你好'.join(['172','253','18','251']))#172你好253你好18你好251

#(3)直接拼接
print('hello''world!')#helloworld!

#(4)使用格式化拼接
print('%s%s'%(s1,s2))#helloworld
print(f'{s1}{s2}')#helloworld
print('{0}{1}'.format(s1,s2))#helloworld


字符串的去重操作

s='heloloedfoerlfdfksldksdsoedf'
#字符串拼接去重操作 not in
news=''
for item in s:
    if item not in news:
        news += item #拼接
print(news)#helodfrks


#使用索引 + not in
news2=''
for i in range(len(s)):
    if s[i] not in news2:
        news2+=s[i]
print(news2)


#通过集合去重+列表排序
new3=set(s)
lst=list(new3)
lst.sort(key=s.index)
print(''.join(lst))
文章版权声明:除非注明,否则均为柳三千运维录原创文章,转载或复制请以超链接形式并注明出处。

目录[+]

取消
微信二维码
微信二维码
支付宝二维码