How do i add spaces in a string that has been reversed? - python

So basically, i am trying to get the user to input something like "123" and recieve the output "3 2 1"
but i cant figure out how to add the spaces
# current code
number = str(input("Type out a number with more then 1 charachter: "))
print("Original number:", number)
print("Number in reverse:", number[::-1])
I apologize in advance, im really new to programming.

Use str.join:
print("Number in reverse:", ' '.join(number[::-1]))
Or use an iterator reversed:
print("Number in reverse:", ' '.join(reversed(number)))

Use str.join:
print("Number in reverse:", " ".join(number[::-1]))

You can use str.join:
print("Number in reverse:", ' '.join(number[::-1]))
Here a space or ' ' is added between the characters.
The join() method returns a string created by joining the elements of
an iterable by string separator. exmaples for iterable objects are
strings and lists.

Related

Sentence trimming and formatting in Python

So I want input sentences like this:
i ) "abcdef"
relation
ii ) "xyzaswdawd"
relation
upto a few thousand rows.
I want to extract the sentences (i.e the text between " " for each line). Can anyone help me with that?
(Sorry if it is a naive question I am new to Python so wanted help with this)
Use regex for this:
import re
s = input()
print(re.findall(r'\"(.*)\"',s))
Would return a list of those words
mySTR = str(input("Input: "))
c=0
Res=""
for i in mySTR:
if i=='"':
if c!=0:
print(Res)
break
c=c+1
else:
Res=Res+i
The following code takes a string input. It starts with a count c and we assign it a value 0.
The count looks for the number for " found in your string.
It finds the first one and increments it by one. The next time it finds a " it will enter an if statement and print the Result.
The result will be anything that isn't a " and contained between two ". We concatenate every character

difference between print(" str", a ) and print("str" + a )

I am a beginner with python3 and I use a lot print or the logging module to follow the code on the console. A simple example below: what's the difference between:
number = "seven"
print("I cooked " , number , " dishes")
and
number = "seven"
print("I cooked " + number + " dishes")
Internally the difference is that this example (no + sign):
number = "seven"
print("I cooked " , number , " dishes")
Is printing 3 separate string objects. "I cooked ", is object 1, number is object 2, and " dishes" is object 3. So this has 3 objects total.
In the second example (with the + sign):
number = "seven"
print("I cooked " + number + " dishes")
the 3 separate strings are first being concatted into 1 new string object before being printed to stdout. So this example has 4 objects total.
The print statement supports multiple ways of parsing values.
number = 'seven'
Examples: Different style of adding argument in print statement
print("I cooked " , number , " dishes")
C-Style formatting (old):
print("I cooked %s dishes" % number)
C-Style formatting (new) using fomat:
print("I cooked {} dishes ".format(number))
f-string style
print(f"I cooked {number} dishes")
String concatenating:
print("I cooked " + number + " dishes")
You don't necessary to stick with one style. You have various options of doing the same.
The operator + can be only used on strings.
The operator , can be used on any type, and adds a space before automatically.
In addition, + can be used not only in printing but to add one string to another while , cant.
(Note that in the two examples you have, by simply running them will show that the results are different, as the first one will have some words separated by double spaces.)
The print() function will take in strings, each string will be printed out with a ' ' between them:
print('hello', 'world')
Output:
hello world
That is because of the keyword argument, sep. By default, sep=' ', that is changeable by simply adding:
print('hello', 'world', sep='\n')
Output:
hello
world
The + operator will not add any separator, it will simply concatenate the strings:
print('hello' + 'world')
Output:
helloworld
As per PEP3105 print is considered as a function taking *args (several positional arguments).
To answer your question, the result is the same; however, your implementation is different. In the first case you give print multiple arguments to print, while in the second case you give print a concatenated string that you would like to print.
when using
number = "seven"
print("I cooked " , number , " dishes")
print gets 3 different objects (3 strings) as arguments, converts them to string and then prints.
However using
number = "seven"
print("I cooked " + number + " dishes")
means that first these three strings are concatenated and then passed as one object to print.
In reality, it means, that if you do for example
print('xxx' + 5 + 'yyy')
it will throw and error, as it is not possible to directly concatenate string and int types.
Also note following example:
#concatenating 3 strings and passing them as one argument to print
>>> print('xxx' + 'a' + 'yyy',sep=',')
xxxayyy
#passing 3 strings as 3 arguments to print
>>> print('xxx','a','yyy',sep=',')
xxx,a,yyy
You can notice, that in first example, although sep is used (thus it should separate 3 strigns with given separator) it does not work, because these strings are concatenated first and then passed as one argument to print. In the second example however, strings are passed as separated arguments, therefore sep=',' works, because print just knows that it should pass the separator between each given string.
Lets say a = "how are you" and b = "goodbye" which are 2 string variables.
If we do print(a, b):
The statement will print first a then b as separate strings outputted on one line:
Output:
> how are you goodbye
If we do print(a + b) the statement will concatenate these two variables a and b together:
Output:
> how are yougoodbye
(here there's no spacing due no white spacing in the print statement or the variables)

How can I extract a number from a string using selenium?

I am doing WebScraping on the Frankfurter Allgemeine Zeitung Archiv and I need to count how many times the word 'Bürokratie' appears in their articles.
From 1st October 2018 to 31st October 2018 the word appeared 75 times.
I have the string "75 Treffer". How can I extract the number 75 from that string using selenium?
This code extract number any way from the string.
# Python3 code to demonstrate
# getting numbers from string
# using List comprehension + isdigit() +split()
# initializing string
test_string = "There are 2 Cars for 8 persons"
# printing original string
print("The original string : " + test_string)
# using List comprehension + isdigit() +split()
# getting numbers from string
res = [int(i) for i in test_string.split() if i.isdigit()]
# print result
print("The numbers list is : " + str(res))
Hope this will help you to address your issue.
Call the split function using " " as the place to split at then cast to an int:
yourString = "75 whatever"
splitString = yourString.split( ' ' )
yourInt = int( splitString[0] )

I cannot get rid of this space

I have the simple code:
answer= input("Have you started your first homework? ")
print("Your answer was:", answer,"!")
However every time I run this it prints the answer there is a space before the "!".
I cannot find a way to make the exclamation follow the answer directly. Why and how can I do that?
If you want to print the answer, you have a few options:
# Multiple args
print("Your answer was: ", answer, "!", sep="")
# String formatting
print("Your answer was: {}!".format(answer))
# String concatenation
print("Your answer was: " + answer + "!")
Python 3.6+:
# f-strings
print(f"Your answer was: {answer}!")
print has an argument called sep which, by default, is set to ' ' (a space). It will add that separator between every argument.
print function automatically adds a space between comma separated arguments.
So if you don't want that comma, don't pass them as separate arguments and use string formatting instead e.g.:
print("Your answer was:", "{}!".format(answer))
Here i've concatenated the strings using str.format:
"{}!".format(answer)
If you're in Python 3.6 or later, you can use f-strings:
f"{answer}!"
You can even use the printf style formatting:
"%s!" % answer
Try this:
print("Your answer was: "+answer"+"!")

Python: Remove words from a given string

I'm quite new to programming (and this is my first post to stackoverflow) however am finding this problem quite difficult. I am supposed to remove a given string in this case (WUB) and replace it with a space. For example: song_decoder(WUBWUBAWUBWUBWUBBWUBC) would give the output: A B C. From other questions on this forums I was able to establish that I need to replace "WUB" and to remove whitespace use a split/join. Here is my code:
def song_decoder(song):
song.replace("WUB", " ")
return " ".join(song.split())
I am not sure where I am going wrong with this as I the error of WUB should be replaced by 1 space: 'AWUBBWUBC' should equal 'A B C' after running the code. Any help or pointing me in the right direction would be appreciated.
You're close! str.replace() does not work "in-place"; it returns a new string that has had the requested replacement performed on it.
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
Do this instead:
def song_decoder(song):
song = song.replace("WUB", " ")
return " ".join(song.split())
For example:
In [14]: song_decoder("BWUBWUBFF")
Out[14]: 'B FF'
Strings are immutable in Python. So changing a string (like you try to do with the "replace" function) does not change your variable "song". It rather creates a new string which you immediately throw away by not assigning it to something. You could do
def song_decoder(song):
result = song.replace("WUB", " ") # replace "WUB" with " "
result = result.split() # split string at whitespaces producing a list
result = " ".join(result) # create string by concatenating list elements around " "s
return result
or, to make it shorter (one could also call it less readable) you can
def song_decoder(song):
return " ".join(song.replace("WUB", " ").split())
Do the both steps in a single line.
def song_decoder(song):
return ' '.join(song.replace('WUB',' ').split())
Result
In [95]: song_decoder("WUBWUBAWUBWUBWUBBWUBC")
Out[95]: 'A B C'

Categories

Resources