1.1 KiB
1.1 KiB
String Manipulation
Shortcuts, cheatsheets, and sample codes that may be frequently used for strings.
How to remove every other letter from a string:
>>> 'abcdefg'[::2]
>'aceg'
To remove all characters after a specific character/substring from a string, you must use the str.replace() method in Python 3.+:
list_str = {'Abc.ex', 'Bcd.ex', 'cde.ex', 'def.jpg', 'efg.jpg'}
new_set = {x.replace('.ex', '').replace('.jpg', '') for x in list_str}
print(new_set)
output:
{'Bcd', 'Abc', 'cde', 'def', 'efg'}
Can also use str.removesuffix('suffix') method which will remove suffix if there is one, and if there isn't will return original word:
text = 'Quickly'
print(text.removesuffix('ly'))
print(text.removesuffix('World'))
output:
Quick
Quickly
the partition method was introduced in python 2.5 and can also be used to get rid of a section.
text = 'text.com/yes/?/noandifwillthisbethere'
head, sep, tail = text.partition('?')
print(head)
output:
text.com/yes/