Python字符轉(zhuǎn)換
更新時(shí)間:2008年09月06日 13:21:35 作者:
Python提供了ord和chr兩個(gè)內(nèi)置的函數(shù),用于字符與ASCII碼之間的轉(zhuǎn)換。
如:
>>> print ord('a')
97
>>> print chr(97)
a
下面我們可以開始來設(shè)計(jì)我們的大小寫轉(zhuǎn)換的程序了:
#!/usr/bin/env python
#coding=utf-8
def UCaseChar(ch):
if ord(ch) in range(97, 122):
return chr(ord(ch) - 32)
return ch
def LCaseChar(ch):
if ord(ch) in range(65, 91):
return chr(ord(ch) + 32)
return ch
def UCase(str):
return ''.join(map(UCaseChar, str))
def LCase(str):
return ''.join(map(LCaseChar, str))
print LCase('ABC我abc')
print UCase('ABC我abc')
輸出結(jié)果:
abc我abc
ABC我ABC
>>> print ord('a')
97
>>> print chr(97)
a
下面我們可以開始來設(shè)計(jì)我們的大小寫轉(zhuǎn)換的程序了:
復(fù)制代碼 代碼如下:
#!/usr/bin/env python
#coding=utf-8
def UCaseChar(ch):
if ord(ch) in range(97, 122):
return chr(ord(ch) - 32)
return ch
def LCaseChar(ch):
if ord(ch) in range(65, 91):
return chr(ord(ch) + 32)
return ch
def UCase(str):
return ''.join(map(UCaseChar, str))
def LCase(str):
return ''.join(map(LCaseChar, str))
print LCase('ABC我abc')
print UCase('ABC我abc')
abc我abc
ABC我ABC
相關(guān)文章
python 自動(dòng)刷新網(wǎng)頁的兩種方法
這篇文章主要介紹了python 自動(dòng)刷新網(wǎng)頁的兩種方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
Python操作Redis數(shù)據(jù)庫的詳細(xì)教程與應(yīng)用實(shí)戰(zhàn)
Redis是一個(gè)高性能的鍵值存儲(chǔ)數(shù)據(jù)庫,支持多種類型的數(shù)據(jù)結(jié)構(gòu),如字符串、哈希表、列表、集合和有序集合等,在Python中,通過redis-py庫可以方便地操作Redis數(shù)據(jù)庫,本文將詳細(xì)介紹如何在Python代碼中操作Redis,需要的朋友可以參考下2024-08-08
python實(shí)現(xiàn)逆波蘭計(jì)算表達(dá)式實(shí)例詳解
這篇文章主要介紹了python實(shí)現(xiàn)逆波蘭計(jì)算表達(dá)式的方法,較為詳細(xì)的分析了逆波蘭表達(dá)式的概念及實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-05-05

