This question already has answers here:
How to strip all whitespace from string
(14 answers)
Closed 4 years ago.
Basically, I'm trying to do a code in Python where a user inputs a sentence. However, I need my code to remove ALL whitespaces (e.g. tabs, space, index, etc.) and print it out.
This is what I have so far:
def output_without_whitespace(text):
newText = text.split("")
print('String with no whitespaces: '.join(newText))
I'm clear that I'm doing a lot wrong here and I'm missing plenty, but, I haven't been able to thoroughly go over splitting and joining strings yet, so it'd be great if someone explained it to me.
This is the whole code that I have so far:
text = input(str('Enter a sentence: '))
print(f'You entered: {text}')
def get_num_of_characters(text):
result = 0
for char in text:
result += 1
return result
print('Number of characters: ', get_num_of_characters(text))
def output_without_whitespace(text):
newtext = "".join(text.split())
print(f'String without whitespaces: {newtext}')
I FIGURED OUT MY PROBLEM!
I realize that in this line of code.
print(f'String without whitespaces: {newtext}')
It's supposed to be.
print('String without whitespaces: ', output_without_whitespace(text))
I realize that my problem as to why the sentence without whitespaces was not printing back out to me was, because I was not calling out my function!
You have the right idea, but here's how to implement it with split and join:
def output_without_whitespace(text):
return ''.join(text.split())
so that:
output_without_whitespace(' this\t is a\n test..\n ')
would return:
thisisatest..
A trivial solution is to just use split and rejoin (similar to what you are doing):
def output_without_whitespace(text):
return ''.join(text.split())
First we split the initial string to a list of words, then we join them all together.
So to think about it a bit:
text.split()
will give us a list of words (split by any whitespace). So for example:
'hello world'.split() -> ['hello', 'world']
And finally
''.join(<result of text.split()>)
joins all of the words in the given list to a single string. So:
''.join(['hello', 'world']) -> 'helloworld'
See Remove all whitespace in a string in Python for more ways to do it.
Get input, split, join
s = ''.join((input('Enter string: ').split()))
Enter string: vash the stampede
vashthestampede
There are a few different ways to do this, but this seems the most obvious one to me. It is simple and efficient.
>>> with_spaces = ' The quick brown fox '
>>> list_no_spaces = with_spaces.split()
>>> ''.join(list_no_spaces)
'Thequickbrownfox'
.split() with no parameter splits a string into a list wherever there's one or more white space characters, leaving out the white space...more details here.
''.join(list_no_spaces) joins elements of the list into a string with nothing betwen the elements, which is what you want here: 'Thequickbrownfox'.
If you had used ','.join(list_no_spaces) you'd get 'The,quick,brown,fox'.
Experienced Python programmers tend to use regular expressions sparingly. Often it's better to use tools like .split() and .join() to do the work, and keep regular expressions for where there is no alternative.
Related
I have a question that ask the user to input a string THE and split it as three different string, output like this T,H,E I tried but output same with input.
def func():
str1=input("Enter String : ")
','.split(str1)
print(str1)
func()
Output
THE
And second question is that ask the user to enter a string T H E S T R I N G and the output should THE STRING when one space occurs remove it and if more then one then replace it whit single space.
Here is my code.
def func2():
str2=input("Enter String :")
for i in str2:
if(i.isspace==True):
del(i)
else:
str2=str2+i
print(str2)
func2()
output is.
T H E S T R I N GTHESTRING
I have no idea how to correct it.
You cannot store the value after splitting and not printing it.
Just change ','.split(str1) with str1 =str1.split(',') and print str1.
Read the documentation for the split method: it doesn't apply to your first problem at all. Instead, the solution is much simpler: take the individual characters and join them with commas:
char_list = list(str1)
str2 = ','.join(char_list)
... and print or return str3. Yes, this can be shortened; I'm teaching you the individual steps.
As the posting guidelines tell you, each question must have a separate posting. I'll leave the other answer for your other posting.
There's a distinction between in-place and standard operators. In-place functions actually change in the input, while standard operators give a result as output, and that output then has to be assigned or passed to something else for it to be used. (Also, you don't have the syntax correct; it should be 'str1.split(',')) The split operator is a standard operator; 'str1.split(',') doesn't affect the value of str1, but instead creates a new result. Since you're not doing anything with that result, it gets thrown away. You could do split_string ='str1.split(',') and then print(new_string) or just print('str1.split(',').
Also, the problem statements "split it as three different string" and "output like this T,H,E" are contradictory. If you want a list of three strings, that would be ['T','H','E']. Saying you want an output of T,H,E makes it sound like you want a single string with commas between the letters.
This question already has answers here:
Python Regex to find a string in double quotes within a string
(6 answers)
Closed 6 years ago.
I'm trying to write a function where the input has a keyword that occurs multiple times in a string and will print the stuff that has double quotation marks between them after the keyword. Essentially...
Input= 'alkfjjiekeyword "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee keyword"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness'
Output= someonehelpmepls
itonlygivesmeoneinsteadofmultiple
If its possible to have the outputs as its own line that would be better.
Here's what I have so far:
def getEm(s):
h = s.find('keyword')
if h == -1
return -1
else:
begin = s.find('"',h)
end = s.find('"', begin+1)
result = s[begin +1:end]
print (result)
Please don't suggest import. I do not know how to do that nor know what it is, I am a beginner.
Let's take some sample input:
>>> Input= 'alkfjjiekeyword "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee keyword"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness'
I believe that one " was missing from the sample input, so I added it.
As I understand it, you want to get the strings in double-quotes that follow the word keyword. If that is the case, then:
def get_quoted_after_keyword(input):
results = []
split_by_keyword = input.split('keyword')
# you said no results before the keyword
for s in split_by_keyword[1:]:
split_by_quote = s.split('"')
if len(split_by_quote) > 1:
# assuming you want exactly one quoted result per keyword
results.append(split_by_quote[1])
return results
>print('\n'.join(get_quoted_after_keyword(Input))
>someonehelpmepls
>itonlygivesmeoneinsteadofmultiple
How it works
Let's look at the first piece:
>>> Input.split('keyword')
['alkfjjie',
' "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee ',
'"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness']
By splitting Input on keyword, we get, in this case, three strings. The second string to the last are all strings that follow the word keyword. To get those strings without the first string, we use subscripting:
>>> Input.split('keyword')[1:]
[' "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee ',
'"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness']
Now, our next task is to get the part of these strings that is in double-quotes. To do that, we split each of these strings on ". The second string, the one numbered 1, will be the string in double quotes. As a simpler example, let's take these strings:
>>> [s.split('"')[1] for s in ('"one"otherstuff', ' "two"morestuff')]
['one', 'two']
Next, we put these two steps together:
>>> [s.split('"')[1] for s in Input.split('keyword')[1:]]
['someonehelpmepls', 'itonlygivesmeoneinsteadofmultiple']
We now have the strings that we want. The last step is to print them out nicely, one per line:
>>> print('\n'.join(s.split('"')[1] for s in Input.split('keyword')[1:]))
someonehelpmepls
itonlygivesmeoneinsteadofmultiple
Limitation: this approach assumes that keyword never appears inside the double-quoted strings.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
Hi all I am pretty new to python coding but have recently stumbled upon a problem, when asking people for names the program will allow numbers, is there a simple way to fix this.
My code is something like this:
print("what is your name?")
name=input()
print("thank you",name,".")
I am not entirely sure that is the exact code but it does those three things. Thank you and sorry it is a bit basic. Also I am using 3.3.2 I think.
You can use str.isalpha to test if a string is all alphabetic characters (letters):
>>> 'abcde'.isalpha()
True
>>> 'abcde1'.isalpha()
False
>>>
If you have a specific character set to test for, you can use all and a generator expression:
chars = set('abcde') # Put the characters you want to test for in here
all(c in chars for c in name)
Also, I used a set instead of a regular string of characters to improve efficiency. Sets have O(1) (constant) complexity with in where as strings have O(n) (linear) complexity. In other words, it is faster to find things in a set than in a string.
Lastly, you can use string.ascii_letters instead of typing out the whole alphabet:
>>> from string import ascii_letters
>>> ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>>
This becomes especially useful if you want to test for all the letters of the alphabet plus another character or so (such as a hyphen):
chars = set(ascii_letters + '-')
There are a couple of ways to address this. One would be to do something like
if name.isalpha():
# it's alphabetic
else:
# it's not - prompt for new input
But this will reject some names that you might like, such as "John Smith" or "Kate O'Conner".
A more careful approach would be something like
if any(map (lambda c: c.isdigit(), name)):
# there's a digit in there, reject it
else:
# it's got no digits, but maybe it still has punctuation that you don't want?
# do further checks as needed
You can also build a whitelist:
import string
allowed_chars = string.ascii_letters+"'"+ "-" + " "
# allow letters, single-quote, hyphen and space
if all([c in allowed_chars for c in name]):
# passes the whitelist, allow it
I'm currently working on a code to translate lines of text into a variation of pig latin,
and one of the requirements is that at any occurrence of a double consonant (bb, cc, dd, etc.)
the string needs to split between those two consonants and reform the word to look like:
"s" + part 2 + part 1 + "s".
The first part of my code is
raw = input("Enter a line to be translated: ")
words = raw.split()
for word in words:
Any help would be greatly appreciated.
Example input/output: "hello, I am Sammy, nice to meet you" = "slohels, I am smysams, nice to meet you"
You might want to use regular expression here...
>>> import re
>>> s = 'hello, I am Sammy, nice to meet you'
>>> re.sub('((\w*([bcdfghjklmnpqrstvwxyz]))(\\3\w*))', 's\\4\\2s', s)
'slohels, I am smySams, nice to meet you'
Almost there... :)
I'll help you on the way a bit.
double_consonants = [2*c for c in 'bcdfghjklmnpqrstvwxz']
for word in raw:
for d_c in double_consonants:
if d_c in word:
# You should be able to finish this bit yourself
You should have a look at the string methods. Tip: Try:
>> s = "I am going to apply for a job".split('pp')
What does that return? Another tip is to use something like the code above, and place it inside a for loop. Maybe you should split the springs into a list of words first?
Edit: The reason I don't give you the entire answer here, is that I suspect that this is a homework assignment.
So I've been learning Python for some months now and was wondering how I would go about writing a function that will count the number of times a word occurs in a sentence. I would appreciate if someone could please give me a step-by-step method for doing this.
Quick answer:
def count_occurrences(word, sentence):
return sentence.lower().split().count(word)
'some string.split() will split the string on whitespace (spaces, tabs and linefeeds) into a list of word-ish things. Then ['some', 'string'].count(item) returns the number of times item occurs in the list.
That doesn't handle removing punctuation. You could do that using string.maketrans and str.translate.
# Make collection of chars to keep (don't translate them)
import string
keep = string.lowercase + string.digits + string.whitespace
table = string.maketrans(keep, keep)
delete = ''.join(set(string.printable) - set(keep))
def count_occurrences(word, sentence):
return sentence.lower().translate(table, delete).split().count(word)
The key here is that we've constructed the string delete so that it contains all the ascii characters except letters, numbers and spaces. Then str.translate in this case takes a translation table that doesn't change the string, but also a string of chars to strip out.
wilberforce has the quick, correct answer, and I'll give the long winded 'how to get to that conclusion' answer.
First, here are some tools to get you started, and some questions you need to ask yourself.
You need to read the section on Sequence Types, in the python docs, because it is your best friend for solving this problem. Seriously, read it. Once you have read that, you should have some ideas. For example you can take a long string and break it up using the split() function. To be explicit:
mystring = "This sentence is a simple sentence."
result = mystring.split()
print result
print "The total number of words is: " + str(len(result))
print "The word 'sentence' occurs: " + str(result.count("sentence"))
Takes the input string and splits it on any whitespace, and will give you:
["This", "sentence", "is", "a", "simple", "sentence."]
The total number of words is 6
The word 'sentence' occurs: 1
Now note here that you do have the period still at the end of the second 'sentence'. This is a problem because 'sentence' is not the same as 'sentence.'. If you are going to go over your list and count words, you need to make sure that the strings are identical. You may need to find and remove some punctuation.
A naieve approach to this might be:
no_period_string = mystring.replace(".", " ")
print no_period_string
To get me a period-less sentence:
"This sentence is a simple sentence"
You also need to decide if your input going to be just a single sentence, or maybe a paragraph of text. If you have many sentences in your input, you might want to find a way to break them up into individual sentences, and find the periods (or question marks, or exclamation marks, or other punctuation that ends a sentence). Once you find out where in the string the 'sentence terminator' is you could maybe split up the string at that point, or something like that.
You should give this a try yourself - hopefully I've peppered in enough hints to get you to look at some specific functions in the documentation.
Simplest way:
def count_occurrences(word, sentence):
return sentence.count(word)
text=input("Enter your sentence:")
print("'the' appears", text.count("the"),"times")
simplest way to do it
Problem with using count() method is that it not always gives the correct number of occurrence when there is overlapping, for example
print('banana'.count('ana'))
output
1
but 'ana' occurs twice in 'banana'
To solve this issue, i used
def total_occurrence(string,word):
count = 0
tempsting = string
while(word in tempsting):
count +=1
tempsting = tempsting[tempsting.index(word)+1:]
return count
You can do it like this:
def countWord(word):
numWord = 0
for i in range(1, len(word)-1):
if word[i-1:i+3] == 'word':
numWord += 1
print 'Number of times "word" occurs is:', numWord
then calling the string:
countWord('wordetcetcetcetcetcetcetcword')
will return: Number of times "word" occurs is: 2
def check_Search_WordCount(mySearchStr, mySentence):
len_mySentence = len(mySentence)
len_Sentence_without_Find_Word = len(mySentence.replace(mySearchStr,""))
len_Remaining_Sentence = len_mySentence - len_Sentence_without_Find_Word
count = len_Remaining_Sentence/len(mySearchStr)
return (int(count))
I assume that you just know about python string and for loop.
def count_occurences(s,word):
count = 0
for i in range(len(s)):
if s[i:i+len(word)] == word:
count += 1
return count
mystring = "This sentence is a simple sentence."
myword = "sentence"
print(count_occurences(mystring,myword))
explanation:
s[i:i+len(word)]: slicing the string s to extract a word having the same length with the word (argument)
count += 1 : increase the counter whenever matched.