-2

How do you find a space within a string using the .find function or a similar function?

I'm trying to create a code that finds a space within a string, so that I can separate the string into two parts.

If this is too vague, or you don't understand, please comment.

v8-E
  • 1,077
  • 2
  • 14
  • 21
  • 1
    You mean if string is " This is Stack Overflow", you need to count number of spaces i.e. 3 in this case ? – Rahul Agarwal Oct 11 '18 at 09:28
  • 1
    Hi, welcome to SO! Please note that this is not a code implementation service, normally people do some effort their own and come here with specific questions. – toti08 Oct 11 '18 at 09:28
  • What have you tried so far? – U13-Forward Oct 11 '18 at 09:28
  • @toti08 All I was asking is how to find a space within a inputted string – Jordan Maertens Oct 11 '18 at 09:33
  • This is very unclear. What do you mean by "find a space"? Detect if one or more are present? Get the index of the space? Or simply split the string on the space? On all spaces? You have to be much more specific. – Thierry Lathuille Oct 11 '18 at 09:35
  • 1
    Possible duplicate of [How to get the position of a character in Python?](https://stackoverflow.com/questions/2294493/how-to-get-the-position-of-a-character-in-python) – Bernhard Barker Oct 11 '18 at 09:35
  • See also: [How to split a string into a list?](https://stackoverflow.com/questions/743806/how-to-split-a-string-into-a-list) – Bernhard Barker Oct 11 '18 at 09:35

3 Answers3

1

Well, not understandable, but i think split:

s='a b'
print(s.split())

It converts to list with two strings

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

You have several ways to find spaces in a string, according to your needs.

You can use the find method to find the most left occurence

your_string.find(' ')

alternatively, you can find the most right occurence

your_string.rfind(' ')

you can also find all occurences with a comprehension list

[index for index, ch in enumerate(your_string) if ch == ' ']

You can also split all strings by space with

your_string.split() #Split by space by default
BlueSheepToken
  • 5,751
  • 3
  • 17
  • 42
0

If you want to count spaces:

a =  "My Testing String"
a.count(' ')
Rahul Agarwal
  • 4,034
  • 7
  • 27
  • 51