I'm newer to Python and When I use .slipt() superfluous one character
txt = "8/"
x = txt.split("/")
print(x)
result is:
['8', '']
but I want the result is:
['8']
how to fix it
I'm newer to Python and When I use .slipt() superfluous one character
txt = "8/"
x = txt.split("/")
print(x)
result is:
['8', '']
but I want the result is:
['8']
how to fix it
You are getting this because .slipt()
Method split a string into a list. Using /, as a separator, split a string into a list with the respect to "/".
In the asked question:
txt = "8/"
x = txt.split("/")
print(x)
You are split the string with respect to "/". You can visualize txt = "8/"
as txt = "8"+"/"+""
.
If you want your output to do this ['8']
. You can use x.remove("")
to remove ""
so the Final Code is:
txt = "8"+"/"+""
x = txt.split("/")
x.remove("")
print(x)
Just use list slicing:
x = txt.split("/")[0]
Prints:
8
But convert it to a list again:
x = list(txt.split("/")[0])
Prints:
['8']
Since your list contains two values, use indexing - [0]
to get the first at the zeroth index.
You can use strip and then split. Strip remove the character in front or back to avoid empty strings
Code:
txt = "8/"
x = txt.strip("/").split("/")
print(x)
It also works if there is leading / in the string.
Code:
txt = "/8/"
x = txt.strip("/").split("/")
print(x)
Output:
['8']
text = "8/"
#Create a list of words from the text
words = text.split("/")
# Remove any empty elements from the list
filtered_list = [word for word in words if word.strip()]
print(filtered_list)
Output: ['8']