python stringstrip方法详解_Python 基础知识全篇-字符串(Strings)
字符串是字符的集合。
單引號和雙引號
字符串可以包含在單引號或雙引號中。
my_string = "This is a double-quoted string."
my_string = 'This is a single-quoted string.'
這種靈活的方式可以讓我們在字符串中包含引號。
quote = "Linus Torvalds once said, 'Any program is only as good as it is useful.'"
多行字符串
當我們需要創(chuàng)建一個多行字符串的時候,可以用三個引號。如下所示:
multiline_string = '''This is a string where I
can confortably write on multiple lines
without worring about to use the escape character "\\" as in
the previsou example.
As you'll see, the original string formatting is preserved.
'''
print(multiline_string)
改變大小寫
你可以很方便的改變字符串的大小寫。如下所示:
first_name = 'eric'
print(first_name)
print(first_name.title())
最常見的大小寫形式是全小寫(lower),首字母大寫(title)和全大寫(upper)。如下所示:
first_name = 'eric'
print(first_name)
print(first_name.title())
print(first_name.upper())
first_name_titled = 'Eric'
print(first_name_titled.lower())
注意:初始字符串沒被改變。
print(first_name)
print(first_name_titled)
你會經常見到這種用法。變量名后跟點和操作名稱,且后跟一組圓括號。圓括號里可能是空的,也可能包含一些數據。
variable_name.action()
在這個例子中,action 是一個方法的名字。title, lower, upper 是內置在 Python 中的函數,可以作用于字符串的方法。
連接字符串
字符串連接示例如下所示:
first_name = 'ada'
last_name = 'lovelace'
full_name = first_name + ' ' + last_name
print(full_name.title())
加號連接兩個字符串。你可以使用任意個加號來連接字符串。
first_name = 'ada'
last_name = 'lovelace'
full_name = first_name + ' ' + last_name
message = full_name.title() + ' ' + \
"was considered the world's first computer programmer."
print(message)
格式化字符串簡介
string_template = 'The result of the calculation of {calc} is {res}'
print("String Template: ", string_template)
print(string_template.format(calc='(3*4)+2', res=(3*4)+2))
空白符
空白符通常指計算機能夠發(fā)現(xiàn)但不可見的字符。諸如空格,制表符,換行符等。
空格很容易創(chuàng)建,基本上在你擁有計算機的時候就會打出空格符。制表符和換行符是由特殊字符連接組成的。
"\t" 代表制表符,"\n" 代表換行符。你可以將它們添加進字符串的任意部分。
print("\tHello everyone!")
print("Hello \teveryone!")
print("\nHello everyone!")
print("\n\n\nHello everyone!")
去除空白符
有時候我們想去除掉字符串開始或者結尾的空白符。Python 中有一些方法可以幫我們做到這點。如下所示:
name = ' eric '
print(name.lstrip())
print(name.rstrip())
print(name.strip())
lstrip 去除左側開端的空白符,rstrip 去除右端結尾的空白符,strip 去除兩端空白符。
看一個更清晰的例子,如下所示:
name = ' eric '
print('-' + name.lstrip() + '-')
print('-' + name.rstrip() + '-')
print('-' + name.strip() + '-')
動手試一試
Someone Said找一條自己喜歡的名言,存儲在變量。結合適當的介紹打印出來。例如:"Ken Thompson once said, 'One of my most productive days was throwing away 1000 lines of code'"。
First Name Cases將你的姓存儲在一個變量中。
分別用 lowercase, Titlecase, UPPERCASE 三種方式打印姓。
Full Name將你的名和姓存儲在不同的變量中,連接它們并打印。
Name Strip將你的姓存儲在變量中。在姓的前后兩端至少各包含兩種空白符。
打印姓。
分別打印出去掉左側空白符,右側空白符,都去掉空白符的姓。
# Ex : Someone Said
# put your code here
# Ex : First Name Cases
# put your code here
# Ex : Full Name
# put your code here
# Ex : Name Strip
# put your code here
總結
以上是生活随笔為你收集整理的python stringstrip方法详解_Python 基础知识全篇-字符串(Strings)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: myBatis xml if、where
- 下一篇: 网管师职业规划(3)