'Extract a string after a number of forward slashes from inside a string
Hy have a string which corresponds to a file location in linux, i want to extract just the part of it that corresponds to the username and that always comes after the 6th forward slash and then store it in a new string variable:
str1 = "/usr/share/nginx/website/orders/jim/17jkyu.xlsx"
n = 0
user = ','
for ch in str1:
if ch == '/':
n += 1
if n == 6:
user.join(ch)
if n == 7:
break
print(user + '\n')
In this case i want to extract jim and put it into the string user. So far is not working
Solution 1:[1]
Split the string then pull the index value.
str1 = "/usr/share/nginx/website/orders/jim/17jkyu.xlsx"
user = str1.split('/')[6]
Solution 2:[2]
You can use the split Python built-in function over the / symbol, and select the 7th element:
str1.split('/')[6]
Solution 3:[3]
You can check if n=6 and the current char is not /, set user to an empty string and concat the character.
str1 = "/usr/share/nginx/website/orders/jim/17jkyu.xlsx"
n = 0
user = ''
for ch in str1:
if ch == '/':
n += 1
if n == 7:
break
if n == 6 and ch != '/':
user += ch
print(user)
Output
jim
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | eatmeimadanish |
| Solution 2 | lemon |
| Solution 3 | The fourth bird |
