简体   繁体   English

如何在Python中仅从字符串中打印特定名称

[英]How to print only specific name from the string in Python

This is my input string: 这是我的输入字符串:

C:\Company\ProjectList\ProjectName\Requriment\..etc

I would like expected output string: 我想要预期的输出字符串:

ProjectName

I want to print only project name from the string. 我只想从字符串中打印项目名称。 Is this possible in Python? 这在Python中可行吗?

You can use os.sep to split by a delimiter. 您可以使用os.sep来分隔定界符。 The benefit of this method is if you move to a different system and your input paths change format, you will not need to modify your code. 此方法的好处是,如果您移至其他系统,并且输入路径更改了格式,则无需修改代码。

Note that, as per your example, we want to access the 4th component in your path when splitting by os.sep . 请注意,按照您的示例,当您通过os.sep分割时,我们想访问路径中的第4个组件。 Since indexing begins at 0 , we index by [3] . 由于索引从0开始,因此我们以[3]索引。

import os

x = r'C:\Company\ProjectList\ProjectName\Requriment'

res = x.split(os.sep)[3]

print(res)

ProjectName

If you certainly know your project structure, split your text then print the part u want. 如果您确实知道您的项目结构,请分割文本,然后打印所需的部分。 In your case for ex: ` C:\\Company\\ProjectList\\ProjectName\\Requriment\\ 以您的情况为例:`C:\\ Company \\ ProjectList \\ ProjectName \\ Requriment \\
This will print what you want: 这将打印您想要的内容:

raw = "Input String: C:\Company\ProjectList\ProjectName\Requriment\..etc"
name = raw.split("\\")[3]

If you don't know the structure for sure, I don't think there is a fast, pythonic way to extract project name. 如果您不确定结构,我认为没有一种快速,Python方式提取项目名称的方法。 You must build a model for name recognition 您必须建立名称识别模型

This will get you the project name: 这将为您获得项目名称:

string = "C:\Company\ProjectList\ProjectName\Requriment\"

project_name = string.split("\\")[3]

This will only work if project name is always the fourth element. 仅当项目名称始终是第四个元素时,这才起作用。

Note that the back slash needs to be escaped with another backslash. 请注意,反斜杠需要与另一个反斜杠一起转义。

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

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