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

柳三千

文章最后更新时间:2025年04月29日

Python 字符串拼接

字符串的拼接方式

(1) 使用 + 号拼接

s1 = 'hello'
s2 = 'world'
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(f-string)
print('{0}{1}'.format(s1, s2))     # helloworld(format方法)

字符串的去重操作

方法1:字符串拼接 + not in

s = 'heloloedfoerlfdfksldksdsoedf'
news = ''
for item in s:
    if item not in news:
        news += item
print(news)  # helodfrks

方法2:索引遍历 + not in

news2 = ''
for i in range(len(s)):
    if s[i] not in news2:
        news2 += s[i]
print(news2)

方法3:集合去重 + 列表排序

new3 = set(s)
lst = list(new3)
lst.sort(key=s.index)  # 按原字符串出现顺序排序
print(''.join(lst))    # 输出顺序与方法1保持一致

关键说明

  1. join() 方法支持自定义连接符
  2. 集合去重会丢失原始顺序,需配合 sort(key=s.index) 保持顺序
  3. not in 方法时间复杂度为 O(n²),适用于小型字符串

```

文章版权声明:除非注明,否则均为柳三千运维录原创文章,转载或复制请以超链接形式并注明出处。

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