-2

So... I tried to get what my string starts with and I tried to see if I can get what my string starts with, with the startswith function. But as I'm trying to use startswith function it just returning True or False. This is how I tried:

str1 = "sdf fds dfs"
str1.startswith()
Negai
  • 13
  • 5

4 Answers4

1

Can you try the following:

str1[0]

Output:

s

If you want multiple items, you can use slicing:

str1[0:3]

Output:

sdf
Jeril
  • 7,858
  • 3
  • 52
  • 69
0

You can use str1[0] for the 's'

Strings are basically arrays. You can access every character with its position.

You can also select intervals with : i.e. str1[0:5] get you the first five characters

startswith(var) confronts var with the first characters i.e. startswith('sdf') startswith('sd') startswith('s') all returns True

Some documentations for strings and startswith()

NicoCaldo
  • 1,171
  • 13
  • 25
0

To add to the above answers, if you want the first word you can use str1.split(" ").

e.g.

str1 = "sdf fds dfs"
str1 = str1.split(" ")
print(str1[0])

prints sdf

Mercury
  • 298
  • 1
  • 11
0

It only returns True, or False, because it checks whether string starts with inputed character example:

_str = "12345"
print(_str.startswith("a")) # -> False
print(_str.startswith("1")) # -> True

So instead use index, e.g:

print(_str[0]) # Looking for first character in string.

In python and in most programming languages indexing starts from 0, so if you need to get access to the first item you will need to write 0 instead of 1, if you want to access the third item, it will be 2, because it starts like this 0, 1, [2], 3 not 1, 2, [3]

Vazno
  • 71
  • 4