I'm trying to figure out how to select a specific character from a string. I know you can use the [0:0] and [0:-0] syntax etc... However I'm trying to do something different.
If a user enters "Hello, my name is [lol] bob [not[really]] john[son]"
or enters "[[[[]]][[][][]"
I'm trying to count how many square brackets have been typed and either left or right.
Thanks a lot guys for the instant response, a lot of help!
You can use str.count method if you only need to count them:
>>>s = "Hello, my name is [lol] bob [not[really]] john[son]"
>>>s.count('[') + s.count(']')
8
May be there have a better way, but it will do:
input = 'Hello, my name is [lol] bob [not[really]] john[son]'
print len(re.findall("\[|\]", input))
Related
So i'm new to Python and i'm going through a Python course I purchased and they have a quiz. The last question was to print the last 6 letters of the string. The code is below:
welcome_message = "Hello and welcome to the land of Python"
print(f"The last 6 letters of the welcome message:\n'{welcome_message}'\nare: '{welcome_message[len(welcome_message)-6:]}'")
The output would then be:
The last 6 letters of the welcome message:
'Hello and welcome to the land of Python'
are: Python
This is from the solution. I am not understanding what's going on here: '{welcome_message[len(welcome_message)-6:]}'
I don't understand why the solution included the len() function.
Why can't I just do '{welcome_message[-6:]}'
?
You'll get the same output with this too.
In python -1 index is same as the last index and when its blank it means starting or ending depending on where you put it. for eg.
welcome_message[:]
will print the entire string.
As for your question you can use welcome_message[34:] which instead of counting yourself a better way of writing is welcome_message[len(welcome_message)-6:].
But an even better way of writing is the solution you pointed out, i.e,
welcome_message[-6:]
print(f"The last 6 letters of the welcome message:\n'{welcome_message}'\nare: '{welcome_message[len(welcome_message)-6:]}'")
Here is what is happening welcome_message is a variable which can have infinite letters/character/number/symbols/strings etc.. which the system does not know first hand...
So welcome_message[len...] first finds how many characters are there in the string, not words... I say characters because we supply len() function with the welcome_message variable which has just 1 string... so thus far i hope I explained what happened till
{welcome_message[len(welcome_message)]} and then its just plain old -6 arithmetic operation from the count that is returned by the len() fn
welcome_message = "Hello and welcome to the land of Python"
print(f"The last 6 letters of the welcome message:\n'{welcome_message}'\nare: '{welcome_message[len(welcome_message)-6:]}'")
Here welcome_message is storing a string which is "Hello and welcome to the land of Python".
while printing if we will add \n in a string it will output a newline in answer.
len(welcome_message)-6 = 39-6 = 33.
in string slicing s[i:] it will give output as a string which includes the character from i to end of the string.
Hence welcome_message[len(welcome_message)-6:] will output the characters from index of 33 to 39th index.
Remember that " " is also a character of the string.
Write a method to replace all spaces in a string with '%20'. You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string.
This is how I tried to solve, but I know I haven't addressed the question correctly where author asks us to assume the additional space at the end and the true length of the string. I am a beginner in programming trying to learn Algorithms and DS, quite a head bagging on this side.
def replace(astring):
alist= list(astring)
for i in range(len(alist)):
if alist[i] == ' ':
alist[i]= '%20'
return (''.join(alist))
print(replace("Mr John Smith "))
Since you are trying to learn algorithms, I think it will be beneficial to leave two hints to help you forward instead of the answer
"Mr John Smith ".rstrip() will strip any space at the end of a string. This means you will not have to worry about any logic for whitespace
Even though the solution works, you are using extra space by creating alist. Maybe try replacing things in the string itself? In Python a string can already by accessed as a string. For example astring[:2] is valid. Also 'hello world!'.replace(' ', 'test') is your friend
You can use the following code :
import urllib.parse
urllib.parse.quote("Mr John Smith ")
Hey Guys Need Your Help Here.
This is my sample code
import random
import string
import re
str=r'im a boy \\x%02X'
result = re.sub('\\\\x%02X', re.escape('\x5c\x5c\x78\x25\x30\x32\x58'), str, 0)
print(" Code=\n", result)
So when i took output from this program. The output is:
Code=
im a boy \\x%02X
But it is supposed to be like this/
Code=
im a boy \x5c\x5c\x78\x25\x30\x32\x58
Why it is not replacing??
There's a number of mistakes in your code, which makes me wonder if r'im a boy \\x%02X' is actually a correct representation of your input.
Assuming it is:
import re
s = r'im a boy \\x%02X'
result = re.sub(r'\\\\x%02X', re.escape(r'\x5c\x5c\x78\x25\x30\x32\x58'), s)
print(result)
Some of the problems with your code:
Why is random in there? And string?
Don't name variables so that they shadow basic types (or any builtins), str is a bad name
Without the r the \x5c[etc] string will turn into the exact same string as you had before, defined as bytes.
Why use the byte representation of the exact same text as a the replacement for the text?
Why tell re.sub to only replace 0 times?
By the way, from what you appear to be trying here, I wonder if you realise that what you're printing and what the actual value of a variable is, isn't exactly the same thing. What you print is the text representation of the value, not the actual value.
You would do well to explain why you're attempting this replacement, as this may be a typical XY problem.
Hello and thanks for helping.
String examples:
"Hello 43543" ---> "43543"
"John Doe 434-234" ---> "434-234"
I need a regex to extract the examples on the right.
I would do it following way:
import re
pattern = r'\d[0-9\-]*'
number1 = re.findall(pattern,'Hello 43543')
number2 = re.findall(pattern,'John Doe 434-234')
print(number1[0]) #43543
print(number2[0]) #434-234
My solution assumes that you are looking for any string starting with digit and with all other characters being digit or -, this mean it will also grab for example 4--- or 9-2-4--- and so on, however this might be not issue in your use case.
I want to note that before writing pattern, you should answer question: what it should match exactly? My pattern works as intended for examples you given, but keep in mind that this do NOT automatically mean it would give desired output with all data you might want to process using it.
If all your strings are like this, you can achieve the same without re:
s = "John Doe 434-234"
n = s.split()[-1]
print(n)
>>> "434-234"
It will split your string on spaces and give you the last field.
Python 2.7 on Windows 10
So, I've started trying to use a function that, in all of my examples, locates the first iterance in a string of the requested word.
Example:
message = "Hello, World."
print(message.find('World'))
and it will return:
7
This works for me. However I'm trying to give a string, then ask if the user would like to locate a word within that string. If the answer is yes, the program is asking which word and the input from the user is being assigned the variable dokokotoba and then I'm trying to find the word dokokotoba.
The program runs fine in all aspects save that every time I try to find a word, it returns -1, which indicates failure. I don't understand why. Is it because I can't use a variable there? If so, I can't see why not.
You have .find('dokokotoba') instead of .find(dokokotoba).
You are looking for the string 'dokokotoba', not the value of the variable. That string is not present in message, no.
Pass in the variable, not a string literal:
message.find(dokokotoba)
Note the lack of quotes there.
Demo:
>>> message = 'foo bar baz'
>>> message.find('bar')
4
>>> dokokotoba = 'bar'
>>> message.find(dokokotoba)
4
>>> message.find('dokokotoba')
-1
The proper way is
message.find(dokokotoba)
and not
message.find('dokokotoba')
In the second case you are simply searching for the string "dokokotoba" in the message.