python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python 字符串字母大小写转换

python实现字符串字母大小写转换的几种方法

作者:一位代码

本文主要介绍了python实现字符串字母大小写转换的几种方法,包括islower()、isupper()、istitle()、lower()、casefold()、upper()、capitalize()、title()和swapcase(),具有一定的参考价值,感兴趣的可以了解一下

在对字符串所含字母单词进行处理时,经常会对其格式进行转换统一。

python自带了一些判断和处理转换的方法。

一、字符串格式判断方法

islower():str.islower(),判断字符串是否全是小写,是返回True,不是返回False

isupper():str.upper(),判断字符串是否全是大写,是返回True,不是返回False

istitle():str.istitle(),判断字符串是否满足标题格式(即字符串的每个单词的首字母为大写,其余字母为小写),是返回True,不是返回False

con = '''that century,
strolled massifs、rivers and buddhist monasteries,
not for taoism,
but meeting with you on passage.《那一世》'''
print('判断字符串是否全为小写:', con.islower())
print('判断字符串是否全为大写:', con.isupper())
print('判断字符串是否为标题格式:', con.istitle())

图片

注:以上方法都只是针对‘a-zA-Z’进行判断,如字符串含其符号、汉字,都忽略不计。如上例中,包含汉字“那一世”、符号“《》”,在判断是否全为小写时,并没有对其进行判断,而是直接忽略,返回为True。

二、字符串转换方法

(一)字符串全部转换为小写

将字符串全部转换成小写,有lower()和casefold()两个方法。

1、lower()用法

str.lower(),只针对ASCII编码,也就是‘A-Z’有效。

con = '''That century, 
strolled massifs、rivers and Buddhist monasteries,
not for Taoism, 
but meeting with you on passage.'''
print('全部转换为小写:\n', con.lower())

图片

2、casefold()用法

str.casefold(),不仅针对‘A-Z’有效,针对其他语言也有效,与lower()函数相比更加强大,python3.3版本引入。​​​​​​

con = '''that century, 
strolled massifs、rivers and Buddhist monasteries,
not for Taoism, 
but meeting with you on passage.'''
print('全部转换为小写:\n', con.casefold())

图片

​​​​​(二)字符串全部转换为大写

upper()用法:str.upper(),将字符串的所有字母转换为大写

con = '''That century, 
strolled massifs、rivers and Buddhist monasteries,
not for Taoism, 
but meeting with you on passage.'''
print('全部转换为大写:\n', con.upper())

图片

(三)字符串第一个字母大写

capitalize()用法:str.capitalize(),将字符串的第一个字母转换成大写,其余全部转换为小写。

con = '''that century, 
strolled massifs、rivers and Buddhist monasteries,
not for Taoism, 
but meeting with you on passage.'''
print('将字符串的第一个字母变为大写,其余小写:\n', con.capitalize())

图片

(四)标题格式字符串转换

title()用法:str.title(),将字符串转换为标题格式,即每个单词的首字母都转换为大写,其余字母为小写。

con = '''that century, 
strolled massifs、rivers and Buddhist monasteries,
not for Taoism, 
but meeting with you on passage.'''
print('满足标题格式,所有英文单词首字母大写,其余英文字母小写:\n', con.title())

图片

(五)大小写互换

swapcase()用法:str.swapcase(),将字符串中原来的大写转换为小写,小写转换为大写。

con = '''that century, 
strolled massifs、rivers and Buddhist monasteries,
not for Taoism, 
but meeting with you on passage.'''
print('字符串大小写互换:\n', con.swapcase())

图片

到此这篇关于python实现字符串字母大小写转换的几种方法的文章就介绍到这了,更多相关python 字符串字母大小写转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文