wtz
wtz

Reputation: 383

String manipulation in Python

I have a randomly generated string from 6 letters in this form, example:

A' B F2 E' B2 A2 C' D2 C D' E2 F

Some letters have " ' " added to them some have number "2". What i want is to add letter "x" to every letter that is on its own.

So it would look like this:

A' Bx F2 E' B2 A2 C' D2 Cx D' E2 Fx

The trick is that it would add the "x" only to those letters that are on their own. No, Bx -> Bx2.

Any ideas?

Upvotes: 0

Views: 192

Answers (7)

Amber
Amber

Reputation: 527478

The split-comprehend-join version:

' '.join(n+'x' if len(n)==1 else n for n in inputstr.split(' '))

The regex version:

>>> inputstr = "A' F B2 C"
>>> re.sub(r'([A-Z])(?=\s|$)', r'\1x', inputstr)
"A' Fx B2 Cx"

In essence, find any uppercase letter not followed by either a space or the end of the string, and replace it with that character followed by an x.

I ran a few tests with timeit; the former (list comprehension) appears to run slightly faster than the latter (about 15-20% faster on average). This does not appear to change no matter the number of replacements that need to be done (a string 10 times as long still has about the same ratio of processing time as the original).

Upvotes: 4

John La Rooy
John La Rooy

Reputation: 304473

>>> ' '.join((i+'x')[:2] for i in items.split())
"A' Bx F2 E' B2 A2 C' D2 Cx D' E2 Fx"

Upvotes: 1

Alex Martelli
Alex Martelli

Reputation: 882751

With a regular expression,

import re
newstring = re.sub(r"\b(\w)(?![2'])", r'\1x', oldstring)

should be fine. If you're allergic to res,

news = ' '.join(x + 'x' if len(x)==1 else x for x in olds.split())

is a concise way of expressing a similar transformation (if length-one is really the only thing you need to check before appending 'x' to an item).

Upvotes: 2

pwdyson
pwdyson

Reputation: 1177

Ugly or Pythonic?

items = "A' B F2 E' B2 A2 C' D2 C D' E2 F".split()

itemsx = ((a+'x' if len(a)==1 else a) for a in items)
out = ' '.join(itemsx)

Upvotes: 3

kepkin
kepkin

Reputation: 1145

Transform your string into list with split()

s = """A' B F2 E' B2 A2 C' D2 C D' E2 F"""

L = s.split(' ')

for i in xrange(len(L)):
  if len(L[i]) == 1:
    L[i] += 'x'

str_out = ' '.join(L)

Upvotes: 5

ghostdog74
ghostdog74

Reputation: 343135

>>> s="A' B F2 E' B2 A2 C' D2 C D' E2 F".split()
>>> import string
>>> letters=list(string.letters)
>>> for n,i in enumerate(s):
...     if i in letters:
...        s[n]=i+"x"
...
>>> ' '.join(s)
"A' Bx F2 E' B2 A2 C' D2 Cx D' E2 Fx"
>>>

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799510

' '.join(n if len(n) == 2 else n + 'x' for n in s.split(' '))

Upvotes: 1

Related Questions