Using .rsplit() not giving desired results

2024/9/21 1:51:49

I want to manipulate a string using .rsplit() so that anything after the last comma in a string of data is split using commas. As an example:

,000

...should be changed to:

,0,0,0,

In order to this I am using the code:

var = string.rsplit(",",1)[1:]
var = "{}".format(",".join(string(var[0])))

Rather than producing data in the desired format, I am instead getting this:

0,00 

This only seems to be happening if all three digits after the last comma are zeros. Other examples that seem to have worked ok are:

,131 to ,1,3,1,
,311 to ,3,1,1,
,330 to 3,3,0,

Can anyone explain why this is?

Thanks

Answer

1) What do the values in the square brackets do?

See Lists in the tutorial for a full explanation, but briefly:

A simple value in the square brackets is an index. If you have a list a = ['a', 'b', 'c', 'd'], then a[0] is 'a', a[1] is 'b', and so on.

A pair of values separated by a colon is a slice: it gives you not a single value from the list, but a smaller list consisting of all of the values. So, a[1:3] is ['b', 'c'].

You can leave off the start or end of a slice, so a[1:] is ['b', 'c', 'd'].

You can use negative numbers for both indices and slices, meaning to count from the end, so a[-1] is 'd', a[-2] is 'c' and a[-3:-1] is ['b', 'c'].


So, when you do this:

line.rsplit(",",1)[1:]

If you look up str.rsplit, you can see that line.rsplit(",", 1) returns a list of 2 strings—everything up to the last comma, and everything after the last comma—unless there were no commas, in which case it returns a list of 1 string—the whole of line.

The [1:] means that you want everything from the second element on. So, if there was a comma, you get a list of 1 string—everything after the last comma; if there was no comma, you get an empty list.


Let's step through your edited code piece by piece.

>>> s = ',000'
>>> split_s = s.rsplit(",", 1)
>>> split_s
['000']
>>> var = split_s[1:]
>>> var
['000']
>>> var0 = var[0]
>>> var0
'000'
>>> svar0 = string(var0)
TypeError: 'str' object is not callable
>>> # ignore that part, I guess?
>>> joined = ",".join(var0)
'0,0,0'
>>> var = "{}".format(joined)
>>> var
'0,0,0'

Notice that two of these steps do absolutely nothing, while one of them raises an exception, and I'm not sure what they were intended to do. And the final result (removing the part that raises an exception) doesn't demonstrate what you claimed you were trying to fix. So your question is completely unanswerable.

At any rate, if you don't understand how your code breaks down into these steps, you shouldn't be writing dense code. Write things as exactly one simple expression per line, make sure you understand exactly what each one is doing (e.g., by printing out the results, as I did), and get all of them working. After that, you can try to make it more concise again.

https://en.xdnf.cn/q/119254.html

Related Q&A

Concatenate numbers in binary [duplicate]

This question already has answers here:Convert int to binary string in Python(36 answers)Closed 7 years ago.When converting a number in binary in Python what you get is the following:b = bin(77) print(…

AttributeError: DataFrame object has no attribute path

Im trying incrementally to build a financial statement database. The first steps center around collecting 10-Ks from the SECs EDGAR database. I have code for pulling the relevant 8-Ks, 10-Ks, and 10-Qs…

two DataFrame plot in a single plot matplotlip

I want to plot two DataFrame in a single plot.Though, I have seen similar post but none seems to work out. First 5 rows of my dataframe looks like this: df1name type start stop stran…

Automate `lxc-attach` through ssh with Python

Question: How do I automate this process, and include all of the password prompts? Machine 1> ssh user2@machine2password: Machine 2> lxc-attach -n 0x1000 Container> ssh user3@machine3password…

Value of a key in a Python dictinary is not updating [duplicate]

This question already has answers here:Appending a dictionary to a list - I see a pointer like behavior(3 answers)Python The appended element in the list changes as its original variable changes(1 answ…

Python - __init__() missing 1 required positional argument:

Im kinda new to python and I cant get past this error: Traceback (most recent call last):File "***", line 63, in <module>bst = Node() TypeError: __init__() missing 1 required positional…

discord py - Custom command prefix doesnt work (no command run)

i have a problem that i cant solve. Im trying to add a prefix switcher for all guilds, that uses my bot. So Ive done that, but currently no command gets triggered and I cant find a solution since hours…

How to use sep parameter in .format?

I just started learning python and Im experimenting new things. isim = input("Name:") soyad = input("Surname:") yaş = input("Age:") edu = input("Education:") ge…

Python table classification

I have different type of data for example:4.5,3.5,U1 4.5,10.5,U2 4.5,6,U1 3.5,10.5,U2 3.5,10.5,U2 5,7,U1 7,6.5,U1I need output:U1: [[4.5, 3.5], [4.5, 6], [5, 7], [7, 6.5]] U2: [[4.5, 10.5], [3.5, 10.5]…

python json.loads / json.load truncates nested json objects?

given the following code: import json foo = {"root":"cfb-score","children":{"gamecode":{"attribute":"global-id"},"gamestate":{&quo…