简体   繁体   English

如何在 Python 中获取字符串的开头?

[英]How do I get the beginning of a string in Python?

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.所以......我试图得到我的字符串以什么开头,我试图看看我是否能用startswith函数得到我的字符串以什么开头。 But as I'm trying to use startswith function it just returning True or False.但是当我尝试使用startswith函数时,它只返回True或False。 This is how I tried:这就是我尝试的方式:

str1 = "sdf fds dfs"
str1.startswith()

Can you try the following:您可以尝试以下方法:

str1[0]

Output:输出:

s

If you want multiple items, you can use slicing:如果你想要多个项目,你可以使用切片:

str1[0:3]

Output:输出:

sdf

You can use str1[0] for the 's'您可以将str1[0]用于's'

Strings are basically arrays.字符串基本上是数组。 You can access every character with its position.您可以访问每个字符及其位置。

You can also select intervals with : ie str1[0:5] get you the first five characters您还可以选择间隔:str1[0:5]获取前五个字符

startswith(var) confronts var with the first characters ie startswith('sdf') startswith('sd') startswith('s') all returns True startswith(var)var与第一个字符对应,即startswith('sdf') startswith('sd') startswith('s') all 返回True

Some documentations for strings and startswith()字符串startswith()的一些文档

To add to the above answers, if you want the first word you can use str1.split(" ").要添加到上述答案,如果您想要第一个单词,您可以使用 str1.split(" ")。

eg例如

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

prints sdf打印 sdf

It only returns True, or False, because it checks whether string starts with inputed character example:它只返回 True 或 False,因为它检查字符串是否以输入的字符示例开头:

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

So instead use index, eg:所以改为使用索引,例如:

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]在 python 和大多数编程语言中,索引从 0 开始,所以如果你需要访问第一项,你需要写 0 而不是 1,如果你想访问第三项,它将是 2,因为它开始像这样 0, 1, [2], 3 而不是 1, 2, [3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM