Slipt in python superfluous one character " "

Question:

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

Asked By: Otis

||

Answers:

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.

See also

Understanding slicing

Answered By: MendelG
x = list(txt.split("/")[0])

or

x = list(txt.split("/")[-2])

Slicing

Answered By: Talha Tayyab

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)
Answered By: Shounak Das

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']
Answered By: The6thSense
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’]

Answered By: kibromhft
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.