基于Python中字符串部分的If语句

2024-04-24 06:39:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习Python,我对基于字符串部分的if语句有一个问题。我在找答案,但没找到有用的。你知道吗

我列出了几个(15个)名字,分为3个小组:

'axxxxxxxx_44'
'bxxxxxxxx_22'
'cxxxxxxxx_2'

我已经创建了一些方法来编辑这些文件,现在我把它放到了for循环中。对于每一个编辑过的子组,都会创建一个单独的目录,我需要把结果放在依赖于\uxx的目录中。你知道吗

我怎么能用if语句来做呢?你知道吗

现在我所有的文件都在同一个主目录下生成。你知道吗

代码示例:

try:
    for i in range(0, len(dir_names)):
        os.mkdir(dir_names[i])
except FileExistsError:
    print("Directory ", dir_names[i], " already exists")

for x in range(0, len(file_names)):
    fileName = '{}'.format(file_names[x])
# here I need (I know how to change dir but problem with if on string):
# if string is ended by _44 change working directory on directory named _44
# else if _22 change working directory on directory named _22
# else _02 to _02
    fileIn = fileName + "{}".format('')
    fileFixed = fileName + "{}{}".format('_out', '.txt')
    fileFinalCSV = fileName + "{}{}".format('_out', '.csv')

Tags: 文件in目录format编辑forifnames
1条回答
网友
1楼 · 发布于 2024-04-24 06:39:10

有很多方法可以做到这一点。你知道吗

  1. 直接检查字符串:

    if dir_name == 'axxxxxxxx_44'
    

    或者

    if '_44' in dir_name
    
  2. 使用str.endswith()

    if dir_name.endswith('_22')
    
  3. 使用str.split()

    if dir_name.split('_')[1] == '44'
    

有一个几乎无限数量的选择,并根据您的具体情况,你应该使用的一个将有所不同。对于这个例子,我将使用选项2。你知道吗

相关问题 更多 >