Python面试题详解--字符串操作

1. 从字符串中找出第一个重复的字符

比如"abcdefgabcdefg"第一个重复的字符是’a’

  • 遍历字符串,将字符存入新的列表中, 如果字符在新的列表中存在, 则返回该字符
def get_first_duplicated_char(string):
    uniq_chars = set()
    for c in list(string):
        if c not in uniq_chars:
            uniq_chars.add(c)
        else:
            return c

  • 对所有字符进行计数
import string

def get_first_duplicated_char(s):
   all_chars = dict(zip(string.printable, [0] * len(string.printable), ))
   for c in s:
       all_chars[c] += 1
       if all_chars[c] == 2:
           return c
2. 对一段字符串中的电子邮件进行脱敏处理

比如把send email to melody_zkm@gmail.com, melody.zkm@alibaba-inc.com and zkm2000@gov.com.cn 中的邮箱地址全部替换成 ******

import re

def encrypt_emais(string):
    match_emails = re.findall(r'(\w+\.*\w+\@\w+\-*\w*\.\w+\.*\w*)', s)
    for email in match_emails:
        string = re.sub(email, '******', string)
    return string
3. 将一段语句翻转, 但是不翻转语句中的单词

s = “I am a student”
return “student a am I”

def reverse_sentence(sentence):
    return ' '.join(reversed(sentence.split(' ')))
4. 两个字符串包含的字符是否完全相同

s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.

字符串只包含小写字符,总共有 26 个小写字符。可以用 HashMap 来映射字符与出现次数。因为键的范围很小,因此可以使用长度为 26 的整型数组对字符串出现的字符进行统计,然后比较两个字符串出现的字符数量是否相同。

from collections import Counter

def if_contains_same_amount_chars(s1, s2):
    count1 = Counter(s1)
    count2 = Counter(s2)

    if count1 == count2:
        return True
    else:
        return False
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值