Split string every nth character from the right?
You can adapt the answer you linked, and use the beauty of mod
to create a nice little one-liner
:
>>> s = '1234567890'
>>> '/'.join([s[0:len(s)%3]] + [s[i:i+3] for i in range(len(s)%3, len(s), 3)])
'1/234/567/890'
and if you want this to auto-add the dot
for the cases like your first example of:
s = '100243'
then you can just add a mini ternary use or
as suggested by @MosesKoledoye
:
>>> '/'.join(([s[0:len(s)%3] or '.']) + [s[i:i+3] for i in range(len(s)%3, len(s), 3)])
'./100/243'
This method will also be faster than reversing
the string
before hand or reversing
a list
.
split-string-every-nth-character with nth+1 separator '0'
You can use a regular expression with capture groups.
import re
instr = '01110100001101001001110100'
outlist = list(sum(re.findall(r'(\d{8})(\d)', instr), ()))
print(outlist)
re.findall()
returns a list of tuples, list(sum(..., ())
flattens it into a single list.
Python split string every n character
Those are called n-grams.
This should work :)
text = "BANANA"
n = 2
chars = [c for c in text]
ngrams = []
for i in range(len(chars)-n + 1):
ngram = "".join(chars[i:i+n])
ngrams.append(ngram)
print(ngrams)
output: ['BA', 'AN', 'NA, 'AN', 'NA']
How to insert a character every nth character in a pandas dataframe column
Let us try findall
with map
(..
means N = 2)
df.mac_address.str.findall('..').map(':'.join)
Out[368]:
0 00;03;E6;A5;84;C2
1 00;03;E6;A5;84;CC
2 00;03;E6;A5;84;DA
3 00;03;E6;A5;84;DC
4 00;03;E6;A5;84;E4
Name: mac_address, dtype: object
Select every nth character from a string
To follow-up on OP's idea ("use the row numbers"). Split the string, fill a matrix with 10 rows, select the first row.
matrix(strsplit(x, "")[[1]], nrow = 10)[1, ]
# [1] "h" "d" "r" "." "j" "x"
You will get a recycling warning, but that will not affect us because we select the first row.
Good'ol charToRaw
:
rawToChar(charToRaw(x)[c(TRUE, rep(FALSE, 9))])
# [1] "hdr.jx"
Related Topics
Syntax Error on Print With Python 3
Tkinter Creating Buttons in For Loop Passing Command Arguments
How to Add Value Labels on a Bar Chart
Why Do Backslashes Appear Twice
What Is the Purpose of the Single Underscore "_" Variable in Python
How to Keep Keys/Values in Same Order as Declared
How Is Returning the Output of a Function Different from Printing It
Rolling or Sliding Window Iterator
How to Make a Sprite Move When Key Is Held Down
Import Multiple CSV Files into Pandas and Concatenate into One Dataframe
Adding a Method to an Existing Object Instance
List of Lists Changes Reflected Across Sublists Unexpectedly