![](/img/trans.png)
[英]string manipulation in python to convert the case of a word that comes next to "caps lock"
[英]How to reverse caps lock in a string in python?
我有一個可以用大寫鎖定寫的字符串。 “帶大寫鎖定”意味着它要么像 tHIS 要么像 THIS。 使用“isupper()”function 很容易檢測到第二種情況,但我無法找到可靠地找到第一種情況的方法。 對於長度為 1 的字符串,我使用“islower()”來檢測它們是否應該大寫,所以這應該不是問題
import re
inp = input()
trutable = ""
for i in inp:
if i.isupper():
trutable += "1"
if i.islower():
trutable += "0"
pattern = re.compile(r'^01')
answ = re.match(pattern, trutable)
if inp.isupper() or answ != None or (len(inp) == 1 and inp.islower()):
inp = inp.capitalize()
print(inp)
您可以遵循以下方法:
s = "hdCdjdC"
print("".join([x.upper() if x.islower() else x.lower() for x in s]))
OUTPUT
HDcDJDc
請你試試:
s = "hELLO wORLD!"
print(s.swapcase())
Output:
Hello World!
對於文本字符替換 python 字符串具有str.maketrans和str.translate方法:
from string import ascii_lowercase as ascii_up, ascii_uppercase as ascii_low
def reverseCase(text):
m = str.maketrans(ascii_low + ascii_up, ascii_up + ascii_low)
return text.translate(m)
for w in ("tata", "TATA", "TaTa", "42"):
print(reverseCase(w))
Output:
TATA
tata
tAtA
42
檢測事物
[...] 要么就像
'tHIS'
[...]
您可以使用:
def isWordStartingLowerAndContinuingUpperCased(word):
"""Check if words starts with lower case and continues upper cased."""
return word[0].islower() and word[1:].isupper()
for w in ("tHIS", "This", "THIS"):
print(w, ":", isWordStartingLowerAndContinuingUpperCased(w))
要得到
tHIS : True
This : False
THIS : False
規范化文本時要注意誤報 - 有一大組單詞屬於全大寫字母,不應更改 - 縮寫:
NBL、美國、MIB、CIA、FBI、NSA、MI6、NASA、DARPA 等
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.