Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Split string
#1
Hello ! I'm looking for a way to approach the result below.
Basically it consist in move the number at the end of each line (including the K) from the other part of the string.
Any ideas, pls?

From:
kajsdas ass 123
kpwpoejxx as lskdl456
kpow jskdj2.22K
kaçsl djsk djskdjdd 13.3K

To:
kajsdas ass 123
kpwpoejxx as lskdl 456
kpow jskdj 2.22K
kaçsl djsk djskdjdd 13.3K
Reply
#2
From this link

import re
mylist = [
'kajsdas ass 123',
'kpwpoejxx as lskdl456',
'kpow jskdj2.22K',
'kaçsl djsk djskdjdd 13.3K'
]

def add_space(text):
    return re.sub(r'(?<=([a-z])|\d)(?=(?(1)\d|[a-z]))', ' ', text)

for string in mylist:
    print(add_space(string))
Output:
kajsdas ass 123 kpwpoejxx as lskdl 456 kpow jskdj 2.22K kaçsl djsk djskdjdd 13.3K
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
Came up with this:

line = "kpwpoejxx as lskdl456"

words = line.split(" ")

last_word = words[-1]

for index in range(len(last_word)):
    if last_word[index].isdigit():
        words[-1] = last_word[:index]
        words.append(last_word[index:])
        line = ' '.join(words)
        break


print(line)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  doing string split with 2 or more split characters Skaperen 22 2,554 Aug-13-2023, 01:57 AM
Last Post: Skaperen
Sad How to split a String from Text Input into 40 char chunks? lastyle 7 1,144 Aug-01-2023, 09:36 AM
Last Post: Pedroski55
  [split] Parse Nested JSON String in Python mmm07 4 1,540 Mar-28-2023, 06:07 PM
Last Post: snippsat
  Split string using variable found in a list japo85 2 1,306 Jul-11-2022, 08:52 AM
Last Post: japo85
  Split string between two different delimiters, with exceptions DreamingInsanity 2 2,042 Aug-24-2020, 08:23 AM
Last Post: DreamingInsanity
  split string enigma619 1 2,080 May-20-2020, 02:47 PM
Last Post: perfringo
  Split string with multiple delimiters and keep the string in "groups" DreamingInsanity 4 6,537 May-12-2020, 09:31 AM
Last Post: DeaD_EyE
  Split a long string into other strings with no delimiters/characters krewlaz 4 2,796 Nov-15-2019, 02:48 PM
Last Post: ichabod801
  input string split Eric7Giants 3 3,030 Nov-13-2019, 07:19 PM
Last Post: Gribouillis
  [split] capitalize dict keys for display in string newbieAuggie2019 3 3,014 Oct-10-2019, 10:50 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020