似乎应该有一个比以下更简单的方法:
import string
s = "string. With. Punctuation?" # Sample string
out = s.translate(string.maketrans("",""), string.punctuation)
Run Code Online (Sandbox Code Playgroud)
在那儿?
我试图text.translate()在Python 3.4中删除给定字符串中不需要的字符.
最小的代码是:
import sys
s = 'abcde12345@#@$#%$'
mapper = dict.fromkeys(i for i in range(sys.maxunicode) if chr(i) in '@#$')
print(s.translate(mapper))
Run Code Online (Sandbox Code Playgroud)
它按预期工作.但是,在Python 3.4和Python 3.5中执行相同的程序会产生很大的差异.
计算时间的代码是
python3 -m timeit -s "import sys;s = 'abcde12345@#@$#%$'*1000 ; mapper = dict.fromkeys(i for i in range(sys.maxunicode) if chr(i) in '@#$'); " "s.translate(mapper)"
Run Code Online (Sandbox Code Playgroud)
Python 3.4程序需要1.3毫秒,而Python 3.5中的相同程序只需要26.4μs.
与Python 3.4相比,Python 3.5有哪些改进使其更快?
在Python中,如何检查字符串是否只包含某些字符?
我需要检查一个只包含a..z,0..9和的字符串.(期间),没有其他性格.
我可以迭代每个字符并检查字符是a ..z或0..9,或.但那会很慢.
我现在还不清楚如何使用正则表达式来完成它.
它是否正确?你能建议一个更简单的正则表达式或更有效的方法吗?
#Valid chars . a-z 0-9
def check(test_str):
import re
#http://docs.python.org/library/re.html
#re.search returns None if no position in the string matches the pattern
#pattern to search for any character other then . a-z 0-9
pattern = r'[^\.a-z0-9]'
if re.search(pattern, test_str):
#Character other then . a-z 0-9 was found
print 'Invalid : %r' % (test_str,)
else:
#No character other then . a-z 0-9 was found
print 'Valid : %r' % (test_str,)
check(test_str='abcde.1')
check(test_str='abcde.1#')
check(test_str='ABCDE.12')
check(test_str='_-/>"!@#12345abcde<')
''' …Run Code Online (Sandbox Code Playgroud) 我正在用scrapy写小爬虫.其中一个XPath包含价格后跟"zł"(波兰货币标记)问题是它被新行字符,空格和非破坏空格混淆.所以当我这样做时:
sel.xpath("div/div/span/span/text()[normalize-space(.)]").extract()
Run Code Online (Sandbox Code Playgroud)
我明白了:
[u'\n 1\xa0740,00 z\u0142\n \n \n ']
Run Code Online (Sandbox Code Playgroud)
我想改变的
[u'1740,00']
Run Code Online (Sandbox Code Playgroud)
或者只是浮动变量.什么是/最好/最简单/最快的方法?
我是 Python 新手,我正在尝试打印字符串中的所有元音。所以如果有人输入“嘿,一切都好吗?” ,所有元音都需要打印...但我不知道如何?(所以这不是关于计算元音,而是关于打印元音)
现在我有这个;
sentence = input('Enter your sentence: ' )
if 'a,e,i,o,u' in sentence:
print(???)
else:
print("empty")
Run Code Online (Sandbox Code Playgroud) 我需要使用 for 循环按照它们出现的顺序打印出 horton 中的元音,这就是我目前所拥有的。
horton = "A person's a person, no matter how small."
vowels = "aeiouAEIOU"
for letters in horton:
if letters == vowels[0:9]:
print(letters)
Run Code Online (Sandbox Code Playgroud) python ×6
string ×3
python-3.x ×2
character ×1
for-loop ×1
loops ×1
printing ×1
punctuation ×1
python-3.5 ×1
regex ×1
scrapy ×1
search ×1
unicode ×1
xpath ×1