0

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

Otis
  • 156
  • 2
  • 11
  • I think it is the same but I just get index = 0 so this very long @fen1x – Otis Dec 29 '22 at 06:44
  • 1
    As mentioned in one of the answers in question that I mentioned - try `print(list(filter(None, x)))` – fen1x Dec 29 '22 at 06:49

5 Answers5

2

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)
Shounak Das
  • 350
  • 12
0

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

MendelG
  • 14,885
  • 4
  • 25
  • 52
0
x = list(txt.split("/")[0])

or

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

Slicing

Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
0

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']
The6thSense
  • 8,103
  • 8
  • 31
  • 65
0
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']

kibromhft
  • 911
  • 1
  • 7
  • 18