简体   繁体   English

Python-如何将字符串的特定部分插入另一个字符串的特定部分

[英]Python - How to insert a specific part of a string into a specific part of another string

I was wondering how to take a string and cut off one part of it and put that part into the beginning of another string 我想知道如何将一个字符串切掉一部分并将其放入另一根字符串的开头

for example: 例如:

string1 = 'abcdefg'
string2 = 'gfedcba

How could I take the first four letters of string one and put them at the beginning of string2 so it looks like this: 我怎样才能将字符串one的前四个字母放在string2的开头,所以看起来像这样:

string1 = 'efg'
string2 = 'abcdgfedcba'

You need to look into Cutting and slicing strings in Python . 您需要研究Python中的字符串切割和切片 You will be able to solve this problem once you go through this tutorial. 阅读完本教程后,您将能够解决此问题。

SPOILERS BELOW 下方的扰流板

If your still stuck, here is a basic example to get you started: 如果您仍然遇到问题,请参考以下基本示例:

>>> string1 = 'abcdefg'
>>> string2 = 'gfedcba'
>>> string2 = string1[:4] + string2  # prepend first four characters from string1
>>> string2
'abcdgfedcba'
>>> string1 = string1[4:] # update string1 to not keep first four characters
>>> string1
'efg'

In the above, [:4] returns everything up to, but not including, the character at position 4. Additionally, [4:] will return every character after and including position 4. 在上面的代码中, [:4]返回所有内容,但包括位置4处的字符。此外, [4:]将返回位置4之后包括位置4)的每个字符。

li = [0,1,2,3,4]
li[start:end:step] li [start:end:step]
eg. 例如。 li=[2,4,5,7]
Now, i want to grab [1,2,3] from this list I can do that by using slicing 现在,我想从此列表中获取[1,2,3],我可以通过切片来实现

new_li=li[1:4]
print(new_li)
[1,2,3]

Similarly the indexing of strings also start from 0 同样,字符串的索引也从0开始

string1 = 'abcdefg'
string2 = 'gfedcba'
string2 = string1[0:4] + string2 #concat 
string1 = string1[4:7]   #slice from index 4 to 7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM