我是新手,正在尝试找到一种方法,在字符串的开头和结尾插入多个"L"。所以如果我的字符串是:
"where did I put my cupcake this morning"
而我想在开头插入1个"L",在结尾插入2个"L",使其看起来像:"Lwhere did I put my cupcake this morningLL",我该怎么做呢?谢谢。
我是新手,正在尝试找到一种方法,在字符串的开头和结尾插入多个"L"。所以如果我的字符串是:
"where did I put my cupcake this morning"
而我想在开头插入1个"L",在结尾插入2个"L",使其看起来像:"Lwhere did I put my cupcake this morningLL",我该怎么做呢?谢谢。
字符串是不可变的,因此您无法向现有字符串中插入字符。 您必须创建一个新的字符串。 您可以使用字符串连接来实现您想要的效果:
yourstring = "L" + yourstring + "LL"
请注意,您也可以通过使用乘法来创建一个由 n 个 L
组成的字符串:m = 1
n = 2
yourstring = ("L" * m) + yourstring + ("L" * n)
为了完整性和配合其他答案:
yourstring = "L%sLL" % yourstring
或者,更加向前兼容Python 3.x:
yourstring = "L{0}LL".format(yourstring)
你也可以使用join函数:
yourstring = ''.join(('L','yourstring','LL'))
结果:
>>> yourstring
'LyourstringLL'
调用第二个位置上的字符:
>>> s = "0123456789"
>>> s[2]
'2'
使用起始位置和结束位置调用range:
>>> s[4:6]
'45'
调用该位置之前的字符串部分:
>>> s[:6]
'012345'
调用该位置之后的字符串部分:
>>> s[4:]
'456789'
将您的字符串插入第5个位置。
>>> s = s[:5] + "L" + s[5:]
>>> s
'01234L56789'
此外,s
与 s[:]
等价。
对于您的问题,您可以使用所有字符串,即
>>> s = "L" + s + "LL"
或者如果"L"
是另一个字符串(例如,我称之为l
),那么您可以使用该代码:
>>> s = l + s + (l * 2)
在C2H5OH的回答基础上,在Python 3.6+中,您可以使用格式化字符串来使它变得更加简洁:
s = "something about cupcakes"
print(f"L{s}LL")
for x in range(0, [howmanytimes you want it at the beginning]):
yourstring = "L" + yourstring
for x in range(0, [howmanytimes you want it at the end]):
yourstring += "L"
foo = "where did I put my cupcake this morning"
bar = 'L'
foobar = f'{bar*10}{foo}'
print(foobar)
您可以将 10
替换为您想在字符串中放置 L 的次数。同样,您也可以对结束位置采取相同的做法。
foo = "where did I put my cupcake this morning"
bar = 'L'
foobar = f'{bar*10}{foo}{bar*10}'
print(foobar)
您可以使用 f-strings 轻松地在字符串前面或后面添加字符串:
text = "where did I put my cupcake this morning"
prepend = "L"
append = "LL"
print(f"{prepend}{text}{append}")
# Result: "Lwhere did I put my cupcake this morningLL"
或者你可以构建一个函数,给你更多的灵活性:
def prepend_and_append(text: str, prepend_char: str, prepend_times: int, append_char: str, append_times: int) -> str:
return f"{prepend_char * prepend_times}{text}{append_char * append_times}"
print(prepend_and_append(text, "L", 1, "L", 2))
# Result: "Lwhere did I put my cupcake this morningLL"