欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python学习之字符串转换

程序员文章站 2022-12-24 11:14:01
配置环境:python 3.6 python编辑器:pycharm 代码如下: ......

配置环境:python 3.6   python编辑器:pycharm

代码如下:

#!/usr/bin/env python
#-*- coding: utf-8 -*-

def strcase():
    "字符串大小写转换"
    print("演示字符串大小写转换")
    print("演示字符串s赋值为:'  this is a python  '")
    s = '  this is a python  '
    print("大写转换成小写:\ts.lower() \t= %s"%(s.lower()))
    print("小写转换成大写:\ts.upper() \t= %s"%(s.upper()))
    print("大小写转换:\t\ts.swapcase() \t= %s"%(s.swapcase()))
    print("首字母大写:\t\ts.title() \t= %s"%(s.title()))
    print('\n')


def strfind():
    "字符串搜索、替换"
    print("演示字符串搜索、替换等")
    print("演示字符串s赋值为:'  this is a python  '")
    s = '  this is a python  '
    print("字符串搜索:\t\ts.find('is') \t= %s"%(s.find('is')))
    print("字符串统计:\t\ts.count('s') \t= %s"%(s.count('s')))
    print("字符串替换:\t\ts.replace('is','is') = %s"%(s.replace('is','is')))
    print("去左右空格:\t\ts.strip() \t=#%s#"%(s.strip()))
    print("去左边空格:\t\ts.lstrip() \t=#%s#"%(s.lstrip()))
    print("去右边空格:\t\ts.rstrip() \t=#%s#"%(s.rstrip()))
    print('\n')


def strsplit():
    "字符串分割、组合"
    print("演示字符串分割、组合")
    print("演示字符串s赋值为:'  this is a python  '")
    s = '  this is a python  '
    print("字符串分割:\t\ts.split() \t= %s"%(s.split()))
    print("字符串组合1: '#'.join(['this','is','a','python']) \t= %s"%('#'.join(['this','is','a','python'])))
    print("字符串组合2: '$'.join(['this','is','a','python']) \t= %s"%('$'.join(['this','is','a','python'])))
    print("字符串组合3: ' '.join(['this','is','a','python']) \t= %s"%(' '.join(['this','is','a','python'])))
    print('\n')

def strtest():
    "字符串测试"
    print("演示字符串测试")
    print("演示字符串s1赋值为:'abcd'")
    s1 = 'abcd'
    print("测试s.isalpha() = %s"%(s1.isalpha()))
    print("测试s.isdigit() = %s"%(s1.isdigit()))
    print("测试s.isspace() = %s"%(s1.isspace()))
    print("测试s.islower() = %s"%(s1.islower()))
    print("测试s.isupper() = %s"%(s1.isupper()))
    print("测试s.istitle() = %s"%(s1.istitle()))

if __name__ == '__main__':
    strcase()
    strfind()
    strsplit()
    strtest()