![](/img/trans.png)
[英]I want to display my EXCEL data with “%” sign. How can i do so by using python
[英]I want to extract numbers which are started with $ sign. for ex: $545
import re
test = 'We four guys, live at 2nd street of Malibeu. I had a cash of $248 in my pocket. I got a ticket with serial number ABC1234.'
arr = []
arr = re.findall(r'[0-9]+', test)
print(arr)
我試過這樣從字符串中獲取數字。 但它只返回字符串。
我也想在數字之前得到$
符號。 我需要打印像ABC1234
這樣的序列號
我得到的輸出是:
[2, 248, 1234]
我需要這樣的輸出:
帶$
符號:
$248
與ABC
:
ABC1234
請幫我解決這個問題
在匹配數字之前,您可以選擇匹配$
或大寫字符。
(?:\$|\b[A-Z]+)?\d+
模式匹配
(?:
非捕獲組
\\$
匹配 $|
或者\\b[AZ]+
一個單詞邊界,匹配 1+ 個大寫字符)?
關閉非捕獲組並使其可選\\d+
匹配 1+ 個數字例子
import re
test = 'We four guys, live at 2nd street of Malibeu. I had a cash of $248 in my pocket. I got a ticket with serial number ABC1234.'
arr = re.findall(r'(?:\$|\b[A-Z]+)?\d+', test)
print(arr)
輸出
['2', '$248', 'ABC1234']
如果您不想只匹配數字,則非捕獲組不應是可選的,您可以在末尾添加單詞邊界\\b
以防止部分匹配:
(?:\$|\b[A-Z]+)\d+\b
import re
test = 'We four guys, live at 2nd street of Malibeu. I had a cash of $248 in my pocket. I got a ticket with serial number ABC1234.'
arr = re.findall(r'(?:\$|\b[A-Z]+)\d+\b', test)
print(arr)
輸出
['$248', 'ABC1234']
我使用此代碼將 $ 和 ABC 組合在一起:
import re
test = 'We four guys, live at 2nd street of Malibeu. I had a cash of $248 in my pocket. I got a ticket with serial number ABC1234.'
arr = []
arr = re.findall(r'(?:\$|ABC)[0-9]+', test)
print(arr)
結果是['$248', 'ABC1234']
我相信您不需要$
符號的re
模塊。 因為有一個內置的 python 方法,你可以使用 - .startswith
和.endswith
。 這是你如何使用它 -
test = '...'
for i in test.split():
if i.startswith('$'):
print('With $ sign: ',i)
if i.startswith('ABC'):
print('With ABC: ',i)
您也可以使用.startswith
作為序列號。 但是,如果序列號中的字母是隨機的並且不是始終以 'ABC' 開頭,則可以使用re
。 所以,你需要匹配后面有數字的字符串,然后你可以這樣做 -
a = re.findall(r'[a-z]+[\d]+|[A-Z]+[\d]+',test)
print(a)
在這里,
[az]+[\\d]+
匹配任何帶有小寫字母和數字的字符串。 例如-abc1200、ABC1234。 如果您不需要小寫字母,請刪除它們。 但是,為了確保,我添加了它們。
|
正則表達式中的Or
運算符
[AZ]+[\\d]+
匹配任何帶有大寫字母和數字的字符串。 這是您需要的模式的主要部分。
正如我所說,如果您不需要匹配小寫字母,則刪除[az]+[\\d]+
和|
因此,將.startswith
用於“$”,將re
用於“序列號”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.