如何替换整数和字符串的特定组合



>我正在尝试用一副带有符号的纸牌替换python列表。

我尝试过使用 Python 替换函数,但我认为最好的解决方案可能是基于正则表达式替换。

期望的结果是这样的:

"Ah" => "A♥"
"5h" => "5♥"

等。

目前,该列表包含如下项目:[玩家姓名], [玩家钱包], [第1张玩家卡], [第2张玩家卡]

这可能是即:

["Don Johnson", 100, "Ks", "5d"]
["Davey Jones", 100, "4c", "3h"]

对此的任何帮助将不胜感激。谢谢。

(根据要求进行编辑以澄清 - 感谢您到目前为止的所有输入!

在这里,我们可以简单地使用四个简单的表达式,并根据需要进行替换:

([AKJQ0-9]{1,2})h
([AKJQ0-9]{1,2})d

同样,其他两个。

演示

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"([AKJQ0-9]{1,2})h"
test_str = ("Ahn"
    "10h")
subst = "\1♥"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
    print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

如果你只有一个卡片列表,那么它可能看起来像这样:

cards = ['2h', '2s', '2c', '2d', '3h', '3s', '3c', '3d', '4h', '4s', '4c', '4d', '5h', '5s', '5c', '5d', '6h', '6s', '6c', '6d', '7h', '7s', '7c', '7d', '8h', '8s', '8c', '8d', '9h', '9s', '9c', '9d', '10h', '10s', '10c', '10d', 'Ah', 'As', 'Ac', 'Ad', 'Kh', 'Ks', 'Kc', 'Kd', 'Jh', 'Js', 'Jc', 'Jd', 'Qh', 'Qs', 'Qc', 'Qd']

如果是这样,那么只需使用字典和理解:

suits = {'h': '♥', 's': '♠', 'c': '♣', 'd': '♦'}
new_cards = [''.join(rank)+suits[suit] for *rank, suit in cards]

为此输出为:

['2♥', '2♠', '2♣', '2♦', '3♥', '3♠', '3♣', '3♦', '4♥', '4♠', '4♣', '4♦', '5♥', '5♠', '5♣', '5♦', '6♥', '6♠', '6♣', '6♦', '7♥', '7♠', '7♣', '7♦', '8♥', '8♠', '8♣', '8♦', '9♥', '9♠', '9♣', '9♦', '10♥', '10♠', '10♣', '10♦', 'A♥', 'A♠', 'A♣', 'A♦', 'K♥', 'K♠', 'K♣', 'K♦', 'J♥', 'J♠', 'J♣', 'J♦', 'Q♥', 'Q♠', 'Q♣', 'Q♦']

对于您的解决方案,您可以定义一个更正卡的函数:

def fix_card(card):
    suits = {'h': '♥', 's': '♠', 'c': '♣', 'd': '♦'}
    *rank, suit = card
    return ''.join(rank)+suits[suit]

然后像这样使用它:

player = ["Don Johnson", 100, "Ks", "5d"]
player[2] = fix_card(player[2])
player[3] = fix_card(player[3])
print(player)
#["Don Johnson", 100, "K♣", "5♦"]
<</div> div class="one_answers">

不,像这样的简单替换不需要正则表达式。只需使用str.replace

>>> cards = ['Ah', '5h']
>>> [s.replace('h', '♥') for s in cards]
['A♥', '5♥']

最新更新