-4

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"

Nitin
  • 17

4 Answers4

1

Looks like you want to keep the first word (which is not "trimming" though). So you do two things

  1. break the string into a list of words (where "word" is something separated by spaces)
  2. take the first element of that list

    words = mystring.split(' ')
    result = words[0]
    
blue_note
  • 27,712
  • 9
  • 72
  • 90
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
  • 7,937
  • 1
  • 16
  • 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 Dec 26 '18 at 18:31
  • I am sorry. That's the same question i am looking for. – Nitin Dec 27 '18 at 18:13
  • @Nitin You need to access the first element from that list. So use str.split(' ')[0] – Bitto 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
  • 47,570
  • 11
  • 100
  • 153