Going character by character in a string and swapping whitespaces with python - 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.

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(' ', '*')

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

Related

how to remove spaces in between of a string in python?

Suppose I have a string : ' Swarnendu Pal is a good boy '
Here I want to remove all the spaces in between the strings, that means the leading and the last spaces should be remain same but all other spaces should be removed. My final expected output will be : ' SwarnenduPalisagoodboy '
Try this... doesn't matter #spaces you have in the start/end... the code will retain them... & remove in between strings...
s = " Swarnendu Pal is a good boy "
start_space, end_space = 0,0
for i in s:
if i == " ":
start_space += 1
else:
break
for i in s[::-1]:
if i == " ":
end_space += 1
else:
break
result = " " * start_space + s.replace(" ","") + " " * end_space
print(result)
# " SwarnenduPalisagoodboy " #### output
Hope this helps...
An attempt at regular expression, which will remove consecutive white space characters with non white space characters outside both ends (I'm not very good at using it yet, and there may be a better solution):
>>> import re
>>> re.sub(r'(?<=[^ ]) +(?=[^ ])', '', ' Swarnendu Pal is a good boy ')
' SwarnenduPalisagoodboy '

Python: Get single words from a string

i'm trying to make a string analyzer in python. I'm starting with this input as example:
toAnalyze= "Hello!!gyus-- lol\n"
and as output i want something like that:
>Output: ['Hello', '!!', 'guys', '--', ' ', 'lol']
I want every gropus sorted in the original order
I have thought to scan all chars in the original string until the "\n" character and i came up whith this solution:
toAnalyze= "Hello!!gyus-- lol\n"
final = ""
for char in toAnalyze:
if char != " \n\t" and char != " " and char != "\n" and char != "\n\t":
final += char
elif char == " " or char == "\n" or char == "\n\t" or char == " \n\t":
if not final.isalnum():
word= ""
thing = ""
for l in final:
if l.isalnum():
word += l
else:
thing += l
print("word: " + word)
print("thing: " + thing )
And my current output is:
>Output: thing: !!-- word: Hellogyus lol
Do you have and idea?
The output wanted :
>Output: ['Hello', '!!', 'guys', '--', ' ', 'lol']
Thanks in advance and have a nice day
I'm not a python guy, but want to help you to get started. This is the working solution which you can try to improve so that it becomes more pythonist:
toAnalyze= 'Hello!!gyus-- lol\n'
word = ''
separator = ''
tokens = []
for ch in toAnalyze:
if ch.isalnum():
word += ch
# we met the first character of a separator, so save a word
if not ch.isalnum() and word:
tokens.append(word)
word = ''
# 1. we met the first alphanumeric after a separator, so save the separator or
# 2. we met a new separator right after another one, also save the old separator
if ch.isalnum() and separator or separator and separator[-1] != ch:
tokens.append(separator)
separator = ''
if not ch.isalnum():
separator += ch
The output for your example is:
['Hello', '!!', 'gyus', '--', ' ', 'lol']

Unexpected outcome, manipulating string on Python

I am writing some code in Python, trying to clean a string all to lower case without special characters.
string_salada_russa = ' !! LeTRas PeqUEnAS & GraNdeS'
clean_string = string_salada_russa.lower().strip()
print(clean_string)
i = 0
for c in clean_string:
if(c.isalpha() == False and c != " "):
clean_string = clean_string.replace(c, "").strip()
print(clean_string)
for c in clean_string:
if(i >= 1 and i <= len(clean_string)-1):
if(clean_string[i] == " " and clean_string[i-1] == " " and clean_string[i+1] == " "):
clean_string = clean_string.replace(clean_string[i], "")
i += 1
print(clean_string)
Expected outcome would be:
#original string
' !! LeTRas PeqUEnAS & GraNdeS'
#expected
'letras pequenas grandes'
#actual outcome
'letraspequenasgrandes'
I am trying to remove the extra spaces, however unsucessfully. I end up removing ALL spaces.
Could anyone help me figure it out? What is wrong in my code?
How about using re?
import re
s = ' !! LeTRas PeqUEnAS & GraNdeS'
s = re.sub(r"[^a-zA-Z]+", " ", s.lower()).strip()
print(s) # letras pequenas grandes
This first translates the letters into lower case (lower), replace each run of non-alphabetical characters into a single blank (re.sub), and then remove blanks around the string (strip).
Btw, your code does not output 'letraspequenasgrandes'. Instead, it outputs 'letrasZpequenasZZZZZgrandes'.
You could get away with a combination of str.lower(), str.split(), str.join() and str.isalpha():
def clean(s):
return ' '.join(x for x in s.lower().split(' ') if x.isalpha())
s = ' !! LeTRas PeqUEnAS & GraNdeS'
print(clean(s))
# letras pequenas grandes
Basically, you first convert to lower and the split by ' '. After that you filter out non-alpha tokens and join them back.
There's no need to strip your string at each iteration of the first for loop; but, other than that, you could keep the first piece of your code:
for c in clean_string:
if (c.isalpha() == False and c != " "):
clean_string = clean_string.replace(c, "")
Then split your string, effectively removing all the spaces, and re-join the word back into a single string, with a single space between each word:
clean_string = " ".join(clean_string.split())

Removing whitespace from the end of string while keeping space in the middle of each letter

The goal of this code is to take a bunch of letters and print the first letter and every third letter after that for the user. What's the easiest way to remove the whitespace at the end of the output here while keeping all the spaces in the middle?
msg = input('Message? ')
for i in range(0, len(msg), 3):
print(msg[i], end = ' ')
str_object.rstrip() will return a copy of str_object without trailing whitespace. Just do
msg = input('Message? ').rstrip()
For what it's worth, you can replace your loop by string slicing:
print(*msg[::3], sep=' ')
n = ' hello '
n.rstrip()
' hello'
n.lstrip()
'hello '
n.strip()
'hello'
What about?
msg = input('Message? ')
output = ' '.join(msg[::3]).rstrip()
print(output)
You can use at least 2 methods:
1) Slicing method:
print(" ".join(msg[0::3]))
2) List comprehension (more readable/powerful):
print(" ".join([letter for i,letter in enumerate(msg) if i%3==0])

Removing all non-alphabet characters from a list

I am building a very simple translator program that uses wordreference.com to look up the meanings of words.
I am not very good at Python (3.4) but I was able to make this
(Also, I know the n = n + 1 thing I have isn't currently working, I did this on purpose to test other things!)
import webbrowser
import sys
trans = True
print('What language will you be translating FROM?')
lang = input()
n = 1
print('Ok, ' + lang + ', what word would you like to translate from ' + (lang) + ' to English?')
while trans == True:
if n > 99:
print('Another one: ')
word = input()
word = (word.lower())
list = word.split()
if lang == 'French':
lang = 'fren'
if lang == 'french':
lang = 'fren'
for word in list:
webbrowser.open('http://www.wordreference.com/' + (lang) + '/' + (str(word)))
n = n + 1
My question is, how would I remove things such as commas, and exclamation points from the list, but NOT apostraphes
My test sentence is 'Je vais bien, merci!', I want it to open the amount of tabs as the words, (which it does), but instead of it being
Je vais bien, merci!
I want it to be
Je vais bien merci
I know how to use
word.isalpha()
But this only makes it so I cannot use the program at all if the words are not alphabetical.
Thanks in adavance!
This will remove non-alphabet characters excepting apostrophes and spaces.
>>> s = "Je vais bien, merci!"
>>> "".join(c for c in s if c.isalpha() or c in " '")
'Je vais bien merci'
Hope it helps!

Categories

Resources