python学习日记-字符串的一些方法

70 阅读2分钟

python的字符串有很多可以使用的方法,常见的有:

your_input = input('请输入你觉得是回文的文字')
# [::-1] 是把字符串变成从右到左
reverse_your_input = your_input[::-1]
if your_input == reverse_your_input:
    print('你输入的是回文')
else:
    print('你输入的不是回文哟')
str1 = 'hello a'
# 首字母大写 Hello a
print(str1.capitalize())
str2 = 'HEllo To Who'
# 大写变小写 hello to who 和lower()方法相比,这个方法适用于所有语言,lower只适用于英语
print(str2.casefold())
str3 = 'hello world Swapcase'
# 大小写反转
print(str3.swapcase())
str4 = "i don't want to work"
# 全变成大写
print(str4.upper())
str5 = 'I WANT MUCH MUCH MONEY'
# 全变成小写
print(str5.lower())
# 每个单词的首字母变大写
str6 = 'this is a title'
print(str6.title())
germany_word_list = 'ich habe eine katze'
# 保证字符长度是40,不够就占位占够40
print(germany_word_list.center(40))
# 左对齐,且长度是40, 不够就占位,从字符串右边起占够40
print(germany_word_list.ljust(40))
# 右对齐,且长度是40,不够就占位,从左边开始占够40
print(germany_word_list.rjust(40))
# 长度保证是40,不够就用0从左开始补够40,可以用在特定数据格式补0print(germany_word_list.zfill(40))
# 长度是45,不够就用自定义的 呀 占位占够45
print(germany_word_list.center(45, '呀'), )
# 左对齐 保证字符长度是45,不够就用自定义的 呀 占位占够45
print(germany_word_list.ljust(45, '呀'))
# 右对齐 保证字符长度是45,不够就用自定义的 呀 占位占够45
print(germany_word_list.rjust(45, '呀'))

打印结果如下: 请输入你觉得是回文的文字12321 你输入的是回文 Hello a hello to who HELLO WORLD sWAPCASE I DON'T WANT TO WORK i want much much money This Is A Title ich habe eine katze
ich habe eine katze
ich habe eine katze 000000000000000000000ich habe eine katze 呀呀呀呀呀呀呀呀呀呀呀呀呀ich habe eine katze呀呀呀呀呀呀呀呀呀呀呀呀呀 ich habe eine katze呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀 呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀呀ich habe eine katze