Select to view content in your preferred language

How to specify location in string?

894
4
Jump to solution
08-03-2023 05:40 AM
Davec43
Regular Contributor

I'm back to trying to remove "T" from layer names in the Drawing Order.

I have 3 layers:

T123T
12T3
T123

 

This will remove all the T's:

layers = act_map.listLayers()
for lyr in layers:
    if "T" in lyr.name:
        lyr.name = lyr.name.replace("T", "")

 

How do I specify the first position in the string? so I'm left with:

123T
12T3
123

 

2 Solutions

Accepted Solutions
SvenR
by
New Contributor

Try this. 

layer.name is a string. So you can ask for the "T" in the first letter with ==. If this is true you change the name. But you will do this only ones. For the first letter... This is why you add the 1 in ("T","",1).

layers = act_map.listLayers()
for lyr in layers:
    if "T" == lyr.name[0]:
        lyr.name = lyr.name.replace("T", "", 1)

 

View solution in original post

Luke_Pinner
MVP Regular Contributor

You can also use the string.lstrip (left strip) method. This will remove the given character from the start of a string, leaving the string untouched if it doesn't start with that character.

 

layers = [l.lstrip("T") for l in act_map.listLayers()]

 

View solution in original post

4 Replies
SvenR
by
New Contributor

Try this. 

layer.name is a string. So you can ask for the "T" in the first letter with ==. If this is true you change the name. But you will do this only ones. For the first letter... This is why you add the 1 in ("T","",1).

layers = act_map.listLayers()
for lyr in layers:
    if "T" == lyr.name[0]:
        lyr.name = lyr.name.replace("T", "", 1)

 

Davec43
Regular Contributor

Awesome it worked, thanks!

0 Kudos
shawinfra
New Contributor

You can directly index into a String, but that doesn‘t seem to be what you want to do anyway, so your question is confusing. Iterators are just one way of splitting at whitespace. There are many short command when working with iterators, such as ”for element in iter“, collect, map, and so on https://mobdro.bio/ .

Luke_Pinner
MVP Regular Contributor

You can also use the string.lstrip (left strip) method. This will remove the given character from the start of a string, leaving the string untouched if it doesn't start with that character.

 

layers = [l.lstrip("T") for l in act_map.listLayers()]