I am kind of noob in python and struck in middle of code. I want to trim my string. For example- my string is "bangalore store 1321" and i want to trim it to "banglore"
Asked
Active
Viewed 65 times
4 Answers
1
Looks like you want to keep the first word (which is not "trimming" though). So you do two things
- break the string into a list of words (where "word" is something separated by spaces)
take the first element of that list
words = mystring.split(' ') result = words[0]
blue_note
- 25,410
- 6
- 56
- 79
1
For a slicing answer:
def sub_string(str, start,end):
return str[start:end]
You can also use split, by definition, this splits by spaces, if any other delimiter needed, you can identity it inside the split arguments split(',')
def split_string(str):
return str.split()
This function will return an array of strings. Choose whichever you want from this array
Mohamed Hamza
- 186
- 2
- 7
-
Hi, I have a transaction data for multiple stores across India. The store name is in like Banglore store 123, Mangalore store 121.. Delhi store 12. I need to filter each store according to their 1st word. using split for my store name column, i am getting output [Banglore, Store, 123] – Nitin Dec 26 '18 at 18:32
0
str="bangalore store 1321"
print(str.split(' ')[0])
Output
bangalore
Bitto Bennichan
- 7,277
- 1
- 13
- 38
-
Hi, I have a transaction data for multiple stores across India. The store name is in like Banglore store 123, Mangalore store 121.. Delhi store 12. I need to filter each store according to their 1st word. using split for my store name column, i am getting output [Banglore, Store, 123] – Nitin Dec 26 '18 at 18:27
-
@Nitin you add a new question. Mention what is the data that you have and output you require. Also update what you have tried so far. – Bitto Bennichan Dec 26 '18 at 18:31
-
-
@Nitin You need to access the first element from that list. So use str.split(' ')[0] – Bitto Bennichan Dec 27 '18 at 18:28
0
You can use str's partition method to avoid creating a list like str.split
>>> first_word, _, _ = s.partition(' ') # _ is a convention for a throwaway variable
>>> print(first_word)
bangalore
str.partition takes one argument - the separator - and returns the parts of the string before and after the first occurrence of the separator.
snakecharmerb
- 36,887
- 10
- 71
- 115