This question already has answers here:
Understanding slicing
(38 answers)
Closed 9 years ago.
I am new to python. Please anybody explain the following string operations
s="abcdefghijklmnop"
print s[:6][::-1] #is it first calculating s[:6] and then operating the result with [::-1] ?
"abcdefghijklmnop"[:6][::-1]
Take first 6 characters (abcdef).
Read the result from the end to the beginning (fedcba).
There is an other better way to get this result:
"abcdefghijklmnop"[5::-1]
Related
This question already has answers here:
How to get the size of a string in Python?
(6 answers)
Closed 1 year ago.
This is what have tried but it's not working
lens("Father")
it's len('Father') not lens('Father')
len(Father)
Your mistake is the 's' at the end of len's'
This question already has answers here:
Understanding negative steps in list slicing
(2 answers)
Closed 1 year ago.
I am learning python and I can't solve this problem:
I am ok to reverse the whole string but I want to get only the "Hello" part
astring = "Hello world!"
I was expecting print(astring[0:4:-1]) would do the work but it does not.
print(astring[5:0:-1]) is better but the H is still missing. I get "olle"
Is there anyway to solve this?
Thank you,
Try this:
print(astring[4::-1])
This question already has answers here:
Python list sort in descending order
(6 answers)
Closed 5 years ago.
This is my code:
#这是一个有关旅行的程序
place=['北京天安门','西安兵马俑','香港游乐园','日本秋叶原']
print(place)
print(sorted(place))
print(place)
place.sorted(reverse=true)
print(place)
When I run my code, something Wrong happens.
place.sorted(reverse=true)
or
sorted(place)
Using the 2nd way, how can I give (reverse=true)?
Just use sorted(place, reverse=True).
This question already has answers here:
Understanding slicing
(38 answers)
Closed 4 months ago.
I am trying to make a program that only prints positions in a string that is greater than this position in the string, first i tried the > but it comes up with "Invalid syntax" and highlights it in red. I tried the comparison greater than but that does the same thing (Because i am not comparing)
What i have tried:
sentence = ("Mark")
print (sentence[> 1])
What i want it to print:
rk
If you have any solutions or alternatives to a greater than operator in Python please let me know and i will give it a go. :)
All you need to do is print (sentence[2:])
For future reference and research, it is called slice.
This question already has answers here:
Why doesn't [01-12] range work as expected?
(7 answers)
Closed 5 years ago.
Im try to match ip addresses and have come up with the following regular expression for python. I just cannot understand why this wont work. Any help would be greatly appreciated!
r"[0-255]\.[0-255]\.[0-255]\.[0-255]"
Because [0-255] means any char between 0 to 2 or 5. switch to something like
r"^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"