How to split a string in Python by 2 or 3, etc [duplicate]

2024/7/7 5:21:32

Does anyone know if it's possible in python to split a string, not necessarily by a space or commas, but just by every other entry in the string? or every 3rd or 4th etc.

For example if I had "12345678" as my string, is there a way to split it into "12", "34", "56", 78"?

Answer

You can use list comprehension:

>>> x = "123456789"
>>> [x[i : i + 2] for i in range(0, len(x), 2)]
['12', '34', '56', '78', '9']
https://en.xdnf.cn/q/120024.html

Related Q&A

.LAS into a .CSV file using python

How to change a .las file into a .csv file? Have been trying myself but no luck no far. I am just looking for something decently short that will save some time when I have to convert big .olas files i…

using pandas read_excel to read from stdin

Note: I have solve this problem as per below:I can use to_csv to write to stdout in python / pandas. Something like this works fine:final_df.to_csv(sys.stdout, index=False)I would like to read in an a…

How to print a string x times based on user input [duplicate]

This question already has answers here:How can I read inputs as numbers?(10 answers)Understanding for loops in Python(4 answers)Closed 1 year ago.I am trying to make a simple application that will pri…

How does .join work in Python?

I want to display each row of a SQL query result on a webpage. I found some code, but I dont understand what this line does.u"<br>".join([u"{0}".format(row.combination) for r…

Login, Navigate and Retrieve data behind a proxy with Python

I want, with a python script, to be able to login a website and retrieve some data. This behind my companys proxy.I know that this question seems a duplicate of others that you can find searching, but …

overflow in exp, python

cant really figure out why this error RuntimeWarning: overflow encountered in exp is showing up. The function Im trying to implement is:Id = lambda t_u, yp: Is * (np.exp((Vin(t_u) - L*yp)/(n_Ut*Ut)) - …

Getting a matlab codes results on python

I have code in matlab whose results I would like to use in python code (as a matrix or as a .dat file). Could anyone tell me how this could be done?

My Status object is not saving in Django

When I enter the shell, I run into the following problem:from users.models import Status from django.utils import timezoneStatus.objects.all() >>> [] p = Status() p.status_time = timezone.date…

Too many instances are running for Django Server

When Django server gets started, I can see only one instance of Django server running in the background. But after a while, I can see multiple instances are running.Output:root@GoldenGate:~# ps |grep p…

Not able to display images from static folder using Django

This is my home.html Im not able to display the images in static/images/ folder. Although *[09/Mar/2020 15:52:09] "GET /static/images/mona.jpg HTTP/1.1" 404 1669 * is displayed in terminal.&l…