简体   繁体   中英

Append a portion of a string to a list

I was wondering how one can append a portion of a string to a list? Is there an option of both appending based on the position of characters in the string, and another option that is able to take a specific character of interest? For instance, If I had the string "2 aikjhakihaiyhgikjewh", could I not only append the part of the string that was in positions 3-4 but also append the "2" as well? I'm a beginner, so I'm still kinda new to this python thing. Thanks.

You can use slicing to reference a portion of a string like this:

>>> s = 'hello world'
>>> s[2:5]
'llo'

You can append to a list using the append method:

>>> l = [1,2,3,4]
>>> l.append('Potato')
>>> l
[1, 2, 3, 4, 'Potato']

Best way to learn this things in python is to open an interactive shell and start typing commands on it. I suggest ipython as it provides autocomplete which is great for exploring objects methods and properties.

You can append a portion of a string to a list by using the .append function.

List = []
List.append("text")

To append several parts of the string you can do the following:

List = []
String = "2 asdasdasd"
List.append(String[0:2] + String[3:5])

This would add both sections of the string that you wanted.

You are describing 2 separate operations: slicing a string , and extending a list . Here is how you can put the two together:

In [26]: text = "2 aikjhakihaiyhgikjewh"

In [27]: text[0], text[3:5]
Out[27]: ('2', 'ik')

In [28]: result = []

In [29]: result.extend((text[0], text[3:5]))

In [30]: result
Out[30]: ['2', 'ik']

Use slicing to accomplish what you are looking for:

mystr = "2 aikjhakihaiyhgikjewh"
lst = list(list([item for item in [mystr[0] + mystr[3:5]]])[0])
print lst

This runs as:

>>> mystr = "2 aikjhakihaiyhgikjewh"
>>> lst = list(list([item for item in [mystr[0] + mystr[3:5]]])[0])
>>> print lst
['2', 'i', 'k']
>>> 

Slicing works by taking certain parts of an object:

>>> mystr
'2 aikjhakihaiyhgikjewh'
>>> mystr[0]
'2'
>>> mystr[-1]
'h'
>>> mystr[::-1]
'hwejkighyiahikahjkia 2'
>>> mystr[:-5]
'2 aikjhakihaiyhgi'
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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