简体   繁体   中英

How to cut strings inside a list in python

For example the list will contain

list1 = ["mathematics", "sciences", "historical"]

and i only need the middle parts of the string

output_list = ["thema", "ience", "stori"]

Python list comprehension. Please read it up, it's useful.

Also, python slicing and indexing. You can read more here .

For the problem you post:

output_list = [word[2:7] for word in list1]

print(output_list) 

You can use string slicing for this:

x = "abcde"
print(x[1:4])  # prints elements [1, 4), i.e., "bcd"

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