簡體   English   中英

查找並替換大寫字符

[英]Find and replace the uppercase characters

我想查找並替換字符串中的大寫字符(如_upperchar )。

例如:輸入: HeLLo Capital Letters

輸出: _He_L_Lo _Capital _Letters

我嘗試過:

print "saran"
value = "HeLLo Capital Letters"
for word in value:
        print word
        if word.isupper():
                char = "_"
                value = value.replace(word,char + word)

print value

我得到的輸出是

_He___L___Lo _Capital ___Letters

請有人幫助我減少多余的下划線。

看看re.sub

>>> import re
>>> re.sub(r'([A-Z])', r'_\1', value)
'_He_L_Lo _Capital _Letters'

您的示例中的問題不在於您在迭代字符串時正在修改字符串。 Python將在for循環的開始處創建iter(value) ,並在此之后更改為value ,因為字符串不可更改,因此不會影響循環。 問題是value.replace將替換字符串中所有出現的內容,例如,由於存在3個大寫L,每個L將得到3個下划線( value.replace('L', '_L') _ value.replace('L', '_L')發生3次)。

只需使用str.join ,如果ch / letter是大寫字母,則在ch之前添加_ ,否則只需保持字母/ ch不變:

s=  "HeLLo Capital Letters"

print("".join(["_" + ch if ch.isupper() else ch for ch in s]))
_He_L_Lo _Capital _Letters

之所以遇到問題,是因為每次您都在整個字符串上調用replace,因此重復的L例如以3 _結尾。

如果在循環開始時添加print value,word ,您將看到發生的情況:

HeLLo Capital Letters H
_HeLLo Capital Letters e
_HeLLo Capital Letters L
_He_LLo Capital Letters L # second L
_He__LLo Capital Letters o # after replacing twice we now have double _
 ........................

使用正則表達式的一些時間表明,列表組合是最好的方法:

In [13]: s = s * 50

In [14]: timeit "".join(["_" + ch if ch.isupper() else ch for ch in s])
10000 loops, best of 3: 98.9 µs per loop

In [15]: timeit  r.sub( r'_\1', s)
1000 loops, best of 3: 296 µs per loop

仔細查看代碼執行過程中發生的情況。 我添加了一些“ print”語句來顯示正在發生的事情:

Replacing 'H' with '_H':
    _HeLLo Capital Letters

Replacing 'L' with '_L':
    _He_L_Lo Capital _Letters

Replacing 'L' with '_L':
    _He__L__Lo Capital __Letters

Replacing 'C' with '_C':
    _He__L__Lo _Capital __Letters

Replacing 'L' with '_L':
    _He___L___Lo _Capital ___Letters

您遇到多個L字符,並對每個字符執行替換L_L ,因此得到:

L_L__L___L L →...

這里的其他解決方案將替換( L_L )應用於字符級別,而不是整個字符串。 這就是為什么他們工作而你的卻不工作的原因。

您的代碼段中的問題是,當您第一次將H更改為_H時,下次您進行迭代時,它將再次考慮H,因為現在它位於第二位置! 因此,無需替換,只需創建一個新字符串即可。

value = "HeLLo Capital Letters"
new_value = ""
for word in value:
        #print(word)
        if word.isupper():
                char = "_"
                new_value += char + word
        else:
            new_value += word

print(new_value) 

如果遇到大寫字符,則執行第一個條件,否則將簡單地附加小寫字符

print "saran"
value = "HeLLo Capital Letters"
print ''.join(['_'+ x if x.isupper() else x for x in value])
value = "HELLO Capital Letters"         
for word in value:                      
    str = ""                            
    if word.isupper():                  
        val = word                      
    output=word.replace(val, "_"+word)  
    str = str + output                  
    print str                           

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM