Python180道面试题 [19:30] 字符串

数据类型

字符串

19.列举 Python 中的基本数据类型?

# 数值型 -- int, float, complex
# 布尔型 -- bool
# 字符串 -- str
# 列表 -- list
# 元组 -- tuple
# 字典 -- dict

20.如何区别可变数据类型和不可变数据类型

可变数据类型:在内存id不变的情况下,数据的值可以改变
不可变数据类型,数据的值不能发生改变,如果值发生改变,那么内存id也会改变

demo_list = [1, 2, 3]
print(id(demo_list)) 
demo_list.append(4)
print(id(demo_list))
# 2302473879816
# 2302473879816
demo_tuple = (1, 2, 3)
print(id(demo_tuple))
demo_tuple = (1, 2, 3, 4)
print(id(demo_tuple))
# 2285588675608
# 2285588740600

21.将"hello world"转换为首字母大写"Hello World"

def first_capital(change_sentence: str)-> str:

    split_list = change_sentence.split()
    for i in range(len(split_list)):
        split_list[i] = split_list[i].capitalize()

    split_list = " ".join(split_list)
    return split_list

if __name__ == '__main__':
    change_sentence = "hello world"
    print(first_capital(change_sentence))

# Hello World

22.如何检测字符串中只含有数字?

demo_str.isdigit()

23.将字符串"ilovechina"进行反转

demo_str = "ilovechina"
print(demo_str[::-1])

list_str = list(demo_str)
list_str.reverse()
print("".join(list_str))

24.Python 中的字符串格式化方式你知道哪些?

(1). 使用%

%s     字符串
%c     字符
%d     十进制(整数)
%i     整数
%u    无符号整数
%o     八进制整数
%x    十六进制整数
%X     十六进制整数大写
%e     浮点数格式1 
%E     浮点数格式2 
%f     浮点数格式3 
%g    浮点数格式4 
%G     浮点数格式5 
%%     文字% 
>>> print("我叫%s,今年%d岁了" % ("小李", 20))
我叫小李,今年20岁了

(2). 通过{}替代%

>>> print("我叫{},今年{}岁了".format("小李", 20))
我叫小李,今年20岁了

25.有一个字符串开头和末尾都有空格,比如“ adabdw ”,要求写一个函数把这个字符串的前后空格都去掉。

demo_str.strip()

26.获取字符串"123456"最后的两个字符。

demo_str[-2:]

27.一个编码为 GBK 的字符串S,要将其转成 UTF-8 编码的字符串,应如何操作

demo_str = demo_str.decode('gbk').encode('utf-8')

28. (1) s = “info:xiaoZhang 33 shandong”,用正则切分字符串输出[‘info’, ‘xiaoZhang’, ‘33’, ‘shandong’]

import re
demo_str = "info:xiaoZhang 33 shandong"
pattern = re.compile(r'\W')
print(pattern.split(demo_str))
# ['info', 'xiaoZhang', '33', 'shandong']

(2) a = "你好 中国 ",去除多余空格只留一个空格。

a.rstrip()

29. (1)怎样将字符串转换为小写

demo_str.lower()

(2)单引号、双引号、三引号的区别?

单引号、双引号可以用来表示一个字符串;
三引号一般用于多行注释,也可以用来表示字符串

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值