回答
''.join(c.lower() for c in s if not c.isspace())
不.Python不是Ruby。
>>> string=""" a b c
... D E F
... g
... """
>>> ''.join( i.lower() for i in string.split() )
'abcdefg'
>>>
OR
>>> ''.join(map(str.lower, string.split()) )
'abcdefg'
您的加入拆分解決方案仍然比John Machin的答案慢很多,使用timeit將其時鐘數設置爲0.733391046524s,對於250k代表,對於他的解決方案,則爲0.413959026337s。以最快的速度前進! – radtek 2017-08-05 03:53:39
這裏使用的解決方案正則表達式:
>>> import re
>>> test = """AB cd KLM
RST l
K"""
>>> re.sub('\s+','',test).lower()
'abcdklmrstlk'
這似乎是最慢的一組,在250k迭代中的0.809034109116s與John Machin的解決方案在0.411396980286s。地圖也比0.582627058029s更快。 – radtek 2017-08-05 03:47:10
怎麼樣一個簡單快速答案嗎?沒有map
,沒有for
環路,...
>>> s = "Foo Bar " * 5
>>> s
'Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar '
>>> ''.join(s.split()).lower()
'foobarfoobarfoobarfoobarfoobar'
>>>
[Python的2.7.1]
>python -mtimeit -s"s='The quick brown Fox jumped over the lazy dogs'" "''.join(c.lower() for c in s if not c.isspace())"
100000 loops, best of 3: 11.7 usec per loop
>python27\python -mtimeit -s"s='The quick brown Fox jumped over the lazy dogs'" "''.join( i.lower() for i in s.split() )"
100000 loops, best of 3: 3.11 usec per loop
>python27\python -mtimeit -s"s='The quick brown Fox jumped over the lazy dogs'" "''.join(map(str.lower, s.split()) )"
100000 loops, best of 3: 2.43 usec per loop
>\python27\python -mtimeit -s"s='The quick brown Fox jumped over the lazy dogs'" "''.join(s.split()).lower()"
1000000 loops, best of 3: 1 usec per loop
+1不妨使用最快,最正確的選項。 – samplebias 2011-04-27 21:56:10
+1,確實是我目前看到的最快的。用timeit模塊確認使用250k迭代0.403948068619s使用split,0.585318088531s使用map。謝謝! – radtek 2017-08-05 03:43:38
- 1. 將所有大寫字母替換爲小寫字母,除了urlencoded字符串
- 2. 刪除字符串中的所有字符但字母
- 3. Python從字符串中刪除字母
- 4. 在Python中刪除字符串中的大寫字母
- 5. 首字母大寫並刪除字符串中的空格
- 6. 如何從字符串中刪除所有字母字符?
- 7. 快速刪除字符串中的所有非字母字符,python
- 8. Perl:除了空白字符串以外的所有字符串
- 9. 刪除所有的空白和所有換行符和字符
- 10. 檢查字符串在PowerShell中的所有小寫字母
- 11. 如何從python中的字符串中刪除小寫字詞
- 12. 刪除空格以外的所有字母數字字符?
- 13. 將字符串轉換爲小寫字母,但所有元字符除外
- 14. SQL Server-刪除字符串中的所有字母
- 15. 從字符串中刪除所有空格和標點符號(不是字母)?
- 16. 從bash中的字符串中刪除所有特殊字符和大小寫
- 17. Shell腳本:刪除字符串中的所有空格字符
- 18. 刪除Rails中字符串的所有空格字符
- 19. 刪除字符串中所有的空格字符前用PHP
- 20. 從字符串中刪除字母字符和空格
- 21. 有選擇地刪除空白字符串後在Python
- 22. Python - 刪除字符串中的空格
- 23. 刪除Python字符串中的空格
- 24. 如何從字符串中刪除所有字母
- 25. Python:替換字符串中的大寫字母和小寫字母
- 26. 修剪字符串,刪除空白
- 27. 刪除字符串中的字母
- 28. 刪除字符串中多餘的空白字符
- 29. C - 刪除字符串中的空白字符
- 30. SQL如何刪除所有的ASCII字符(空白字段輸入後空白)
是正則表達式的東西是在Python用得少? – 2011-04-27 04:04:11
正則表達式通常不是必需的。 – 2011-04-27 04:05:43
@DutrowLLC,它們通常不是必需的,但有時它們是不可或缺的。 – ghostdog74 2011-04-27 04:07:49