Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Going character by character in a string and swapping whitespaces with python

Okay so I have to switch ' ' to *s. I came up with the following

def characterSwitch(ch,ca1,ca2,start = 0, end = len(ch)):
    while start < end:
        if ch[start] == ca1:
            ch[end] == ca2
        start = start + 1
sentence = "Ceci est une toute petite phrase."
print characterSwitch(sentence, ' ', '*')
print characterSwitch(sentence, ' ', '*', 8, 12)
print characterSwitch(sentence, ' ', '*', 12)
print characterSwitch(sentence, ' ', '*', end = 12)

Assigning len(ch) doesn't seem to work and also I'm pretty sure this isn't the most efficient way of doing this. The following is the output I'm aiming for:

Ceci*est*une*toute*petite*phrase.
Ceci est*une*toute petite phrase.
Ceci est une*toute*petite*phrase.
Ceci*est*une*toute petite phrase.
like image 660
user3413472 Avatar asked May 30 '16 17:05

user3413472


People also ask

How do you interchange a character in a string in python?

1: Python swap first and last character of stringDefine a function, which is used to swap characters of given string. Allow user to input a string. Call swap() with [ass the string as an argument to a function. Print result.

How do you check for Whitespaces in a string in python?

Python String isspace() The isspace() method returns True if there are only whitespace characters in the string. If not, it return False. Characters that are used for spacing are called whitespace characters.

Can I reassign a string in Python?

Python strings are "immutable" which means they cannot be changed after they are created (Java strings also use this immutable style). Since strings can't be changed, we construct *new* strings as we go to represent computed values.

How do you remove multiple spaces from a string in Python?

Using sting split() and join() You can also use the string split() and join() functions to remove multiple spaces from a string.


2 Answers

Are you looking for replace() ?

sentence = "Ceci est une toute petite phrase."
sentence = sentence.replace(' ', '*')
print sentence
# Ceci*sest*sune*stoute*spetite*sphrase.

See a demo on ideone.com additionally.

For your second requirement (to replace only from the 8th to the 12th character), you could do:

sentence = sentence[8:12].replace(' ', '*')
like image 74
Jan Avatar answered Nov 12 '22 13:11

Jan


Assuming you have to do it character by character you could do it this way:

sentence = "this is a sentence."
replaced = ""

for c in sentence:
    if c == " ":
        replaced += "*"
    else:
        replaced += c

print replaced
like image 39
sknt Avatar answered Nov 12 '22 12:11

sknt