【问题标题】:paste0 like function in python for multiple stringspython中的paste0类似函数用于多个字符串
【发布时间】:2018-11-12 04:09:29
【问题描述】:

我想要实现的很简单,在 R 中我可以做类似的事情

paste0("https\\",1:10,"whatever",11:20),

如何在 Python 中做到这一点?我发现了一些东西here,但只允许:

paste0("https\\",1:10).

任何人都知道如何解决这个问题,这一定很容易做到,但我找不到。

【问题讨论】:

  • 你可以使用 list comprehensionzip() 来解决这个问题。

标签: python string-concatenation


【解决方案1】:

根据您提供的链接,应该可以:

["https://" + str(i) + "whatever" + str(i) for i in xrange(1,11)]

给出以下输出:

['https://1whatever1', 'https://2whatever2', 'https://3whatever3', 
'https://4whatever4', 'https://5whatever5', 'https://6whatever6', 
'https://7whatever7', 'https://8whatever8',
'https://9whatever9', 'https://10whatever10']

编辑:

这应该适用于paste0("https\\",1:10,"whatever",11:20)

paste_list = []

for i in xrange(1,11):

    # replace {0} with the value of i
    first_half = "https://{0}".format(i)

    for x in xrange(1,21):

        # replace {0} with the value of x
        second_half = "whatever{0}".format(x)

        # Concatenate the two halves of the string and append them to paste_list[]
        paste_list.append(first_half+second_half)

print paste_list

【讨论】:

  • 嗨@ResetACK,感谢您的回复,这确实有效。抱歉我没把问题说清楚,如果改成paste0("https\\",1:10,"whatever",11:20)怎么办? BYW,也在问题中进行了编辑。
  • @JasonGoal 编辑了新答案,让我知道你的进展情况
  • @ResetACKm,您的解决方案非常适合我。 Rishikesh Agrawani 的答案更容易实现,尤其是第一个,所以我将功劳归功于他。无论如何,感谢您的解决方案。
【解决方案2】:

@Jason,我建议您使用以下两种方法中的任何一种来完成此任务。

✓ 通过使用 list comprehensionzip() 函数创建文本列表。

注意:要在屏幕上打印\,请使用转义序列\\。见List of escape sequences and their use

如果您认为此答案不能满足您的问题,请发表评论。我将根据您的输入和预期输出更改答案。

texts = ["https\\\\" + str(num1) + "whatever" + str(num2) for num1, num2 in zip(range(1,10),range(11, 20))]

for text in texts:
    print(text)

"""
https\\1whatever11
https\\2whatever12
https\\3whatever13
https\\4whatever14
https\\5whatever15
https\\6whatever16
https\\7whatever17
https\\8whatever18
https\\9whatever19
"""

✓ 通过定义一个简单的函数 paste0() 实现上述逻辑以返回文本列表。

import json

def paste0(string1, range1, strring2, range2):
    texts = [string1 + str(num1) + string2 + str(num2) for num1, num2 in zip(range1, range2)]

    return texts


texts = paste0("https\\\\", range(1, 10), "whatever", range(11, 20))

# Pretty printing the obtained list of texts using Jon module
print(json.dumps(texts, indent=4))

"""
[
    "https\\\\1whatever11",
    "https\\\\2whatever12",
    "https\\\\3whatever13",
    "https\\\\4whatever14",
    "https\\\\5whatever15",
    "https\\\\6whatever16",
    "https\\\\7whatever17",
    "https\\\\8whatever18",
    "https\\\\9whatever19"
]
"""

【讨论】:

  • 谢谢,一个可行且易于实施的解决方案,将其作为答案。
  • 感谢您的宝贵反馈@Jason
猜你喜欢
  • 1970-01-01
  • 2018-05-01
  • 2021-06-28
  • 2010-09-21
  • 1970-01-01
  • 2019-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多