paste0 like python中的函数用于多个字符串

时间:2018-06-02 03:18:08

标签: python string-concatenation

我想要实现的是简单的,在R中我可以做像

这样的事情

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

如何在Python中执行此操作?我发现了here,但只允许:

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

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

2 个答案:

答案 0 :(得分:2)

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

✓使用列表理解 zip()功能创建文本列表。

  

注意:要在屏幕上打印\,请使用转义序列\\。请参阅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"
]
"""

答案 1 :(得分: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