0

I have just started to learn python and would like help using string.replace(x,y).

Specifically, replacing all to X's and x's depending whether the letter was originally capitalized or not.

e.g. John S. Smith -> Xxxx X. Xxxxx

What I have created currently is below.

print("Enter text to translate:", end ="")
sentence = input ()
replaced = sentence.replace("", "x") 
print(replaced)

However when I input text like "John Smith". I am returned with "xJxoxhxnx xSx.x xSxmxixtxhx".

Thank you in advance!

Edit: Although string.replace(x,y) may be longer to perform, I'd like to slowly build on my knowledge before finding faster and shorter ways to perform the same operation. I'd highly appreciate it if it was explained in terms of string.replace(x, y) instead of re.sub

Edit2: I have been notified that string.replace is the wrong tool to use. Thank you for your help! I will be reading into re.sub instead.

Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
pete
  • 1
  • 2
  • 4
  • 2
    You're replacing `''` with `'x'`, and not the other way around. Have a good old look at the manual for the function: [str.replace](https://docs.python.org/3/library/stdtypes.html#str.replace). Notice how old comes first, and new last in the argument list? – Torxed Nov 04 '17 at 12:32
  • `string.replace` is the wrong tool for this. – Stefan Pochmann Nov 04 '17 at 12:34
  • 1
    To indicate that your question is solved, you should just mark one of the answers as _accepted_; you should not change the title. – mshsayem Nov 04 '17 at 12:56

7 Answers7

3
import re
print("Enter text to translate:", end ="")
sentence = input()
replaced = re.sub("[A-Z]", 'X', re.sub("[a-z]", 'x', sentence))
print replaced

Use re.sub to replace individual character of string or iterate through the string.

Mahesh Karia
  • 2,045
  • 1
  • 12
  • 23
3

If you insist on using replace even though it's the wrong tool for the job (because it can only replace one letter at a time and has to go through the whole string every time), here's a way:

>>> s = 'John S. Smith'
>>> for c in s:
        if c.islower():
            s = s.replace(c, 'x')
        if c.isupper():
            s = s.replace(c, 'X')

>>> s
'Xxxx X. Xxxxx'

And a somewhat neat more efficient way:

>>> ''.join('x' * c.islower() or 'X' * c.isupper() or c for c in s)
'Xxxx X. Xxxxx'

And a regex way:

>>> re.sub('[A-Z]', 'X', re.sub('[a-z]', 'x', s))
'Xxxx X. Xxxxx'
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
2

Not the correct usecase for string replace. There are 2 things that you can do:

2

Plain way:

>>> my_string = "John S. Smith"
>>> replaced = ''
>>> for character in my_string:
    if character.isupper():
        replaced += 'X'
    elif character.islower():
        replaced += 'x'
    else:
        replaced += character    

>>> replaced
'Xxxx X. Xxxxx'

One liner:

>>> ''.join('x' if c.islower() else 'X' if c.isupper() else c for c in my_string)
'Xxxx X. Xxxxx'
mshsayem
  • 17,557
  • 11
  • 61
  • 69
1
print("Enter text to translate:", end ="")
sentence = input ()
replaced = ''.join(['x' if (i>='a' and i<='z') else 'X' if (i>='A' and i<='Z') else i for i in sentence])
print(replaced)
0

** edit fixed code **

Try this instead, it is a bit of a simple and easily breakable example but this is what you would need to achieve what you want:

s = "Testing This"
r = ""

for c in s:
    if c.isalpha():
        if c.islower():
            r += "x"
        else:
            r += "X"
    else:
        r += c

print(r)
Polymer
  • 1,108
  • 1
  • 9
  • 17
0

You can use the re module, and provide re.sub with a callback function to achieve this.

import re

def get_capital(ch):
    if ch.isupper():
        return "X"
    return "x"

def get_capitals(s):
    return re.sub("[a-zA-Z]", lambda ch: get_capital(ch.group(0)), s)

print(get_capitals("John S. Smith"))

Has the output:

Xxxx X. Xxxxx

As a matter of style, I've not condensed any of this into lambdas or one-liners, although you probably could.

This will be significantly faster than just repeated concatenation.

Izaak van Dongen
  • 2,450
  • 13
  • 23