> For the complete documentation index, see [llms.txt](https://zeliang-yao.gitbook.io/my-note-zeliang-yao/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zeliang-yao.gitbook.io/my-note-zeliang-yao/useful/untitled-2.md).

# String

有关字符串的常用方法:

### Split and format <a href="#split-and-format" id="split-and-format"></a>

```python
latitude = '37.24N'
longitude = '-115.81W'
'Coordinates {0},{1}'.format(latitude,longitude)
>>>   'Coordinates 37.24N,-115.81W'
```

```python
f'Coordinates {latitude},{longitude}'
>>>'Coordinates 37.24N,-115.81W'
```

```python
'{0},{1},{2}'.format(*('abc'))
>>>'a,b,c'
```

```python
coord = {"latitude":latitude,"longitude":longitude}
'Coordinates {latitude},{longitude}'.format(**coord)
>>>'Coordinates 37.24N,-115.81W'
```

### **Access argument’s attribute** <a href="#access-argument-s-attribute" id="access-argument-s-attribute"></a>

```python
class Point:
    def __init__(self,x,y):
        self.x,self.y = x,y
    def __str__(self):
        return 'Point({self.x},{self.y})'.format(self = self)
    def __repr__(self):
        return f'Point({self.x},{self.y})'
```

```python
test_point = Point(4,2)
test_point
>>>    Point(4,2)
```

```python
str(Point(4,2))
>>>'Point(4,2)'
```

### **Replace with %s , %r**  <a href="#replace-with-s-r" id="replace-with-s-r"></a>

```python
" repr() shows the quote {!r}, while str() doesn't:{!s} ".format('a1','a2')
>>> " repr() shows the quote 'a1', while str() doesn't:a2 "

```

### **Align**  <a href="#align" id="align"></a>

```python
'{:<30}'.format('left aligned')
>>>'left aligned                  '
```

```python
'{:>30}'.format('right aligned')
>>>'                 right aligned'
```

```python
'{:^30}'.format('centerd')
>>>'           centerd            '
```

```python
'{:*^30}'.format('centerd')
>>>'***********centerd************'
```

### **Replace with %x , %o**  <a href="#replace-with-x-o" id="replace-with-x-o"></a>

```python
"int:{0:d}, hex:{0:x}, oct:{0:o}, bin:{0:b}".format(42)
>>>'int:42, hex:2a, oct:52, bin:101010'
```

```python
'{:,}'.format(12345677)
>>>'12,345,677'
```

### **Percentage**  <a href="#percentage" id="percentage"></a>

```python
points = 19
total = 22
'Correct answers: {:.2%}'.format(points/total)
>>>'Correct answers: 86.36%'
```

### **Date**  <a href="#date" id="date"></a>

```python
import datetime as dt
f"{dt.datetime.now():%Y-%m-%d}"
>>>'2019-03-27'
```

```python
f"{dt.datetime.now():%d_%m_%Y}"
>>>'27_03_2019'
```

```python
today = dt.datetime.today().strftime("%d_%m_%Y")
today

'27_03_2019'
```

### **Split without parameters**  <a href="#split-without-parameters" id="split-without-parameters"></a>

```python
"this is a  test".split()
>>>['this', 'is', 'a', 'test']
```

### **Concatenate** : <a href="#concatenate" id="concatenate"></a>

```python
'do'*2
>>>'dodo'
```

```python
orig_string ='Hello'
orig_string+',World'
>>>'Hello,World'
```

```python
full_sentence = orig_string+',World'
full_sentence
>>>'Hello,World'
```

### **Check string type, slice，count，strip** : <a href="#check-string-type-slice-count-strip" id="check-string-type-slice-count-strip"></a>

```python
strings = ['do','re','mi']
', '.join(strings)
>>>'do, re, mi'
```

```python
'z' not in 'abc'
>>> True
```

```python
ord('a'), ord('#')
>>> (97, 35)
```

```python
chr(97)
>>>'a'
```

```python
s = "foodbar"
s[2:5]
>>>'odb'
```

```python
s[:4] + s[4:]
>>>'foodbar'
```

```python
s[:4] + s[4:] == s
>>>True
```

```python
t=s[:]
id(s)
>>>1547542895336
```

```python
id(t)
>>>1547542895336
```

```python
s is t
>>>True
```

```python
s[0:6:2]
>>>'fob'
```

```python
s[5:0:-2]
>>>'ado'
```

```python
s = 'tomorrow is monday'
reverse_s = s[::-1]
reverse_s
>>>'yadnom si worromot'
```

```python
s.capitalize()
>>>'Tomorrow is monday'
```

```python
s.upper()
>>>'TOMORROW IS MONDAY'
```

```python
s.title()
>>>'Tomorrow Is Monday'
```

```
s.count('o')
>>> 4
```

```python
"foobar".startswith('foo')
>>>True
```

```python
"foobar".endswith('ar')
>>>True
```

```python
"foobar".endswith('oob',0,4)
>>>True
```

```python
"foobar".endswith('oob',2,4)
>>>False
```

```python
"My name is yo, I work at xx".find('yo')
>>>11
```

```python
"My name is ya, I work at Gener".find('gent')
>>>-1
```

```python
"abc123".isalnum()
>>>True
```

```python
"abc%123".isalnum()
>>>False
```

```python
"abcABC".isalpha()
>>>True
```

```python
"abcABC1".isalpha()
>>>False
```

```python
'123'.isdigit()
>>>True
```

```python
'123abc'.isdigit()
>>>False
```

```python
'abc'.islower()
>>>True
```

```python
"This Is A Title".istitle()
>>>True
```

```python
"This is a title".istitle()
>>>False
```

```python
'ABC'.isupper()
>>>True
```

```python
'ABC1%'.isupper()
>>>True
```

```python
'foo'.center(10)
>>>'   foo    '
```

```python
'   foo bar baz    '.strip()
>>>'foo bar baz'
```

```python
'   foo bar baz    '.lstrip()
>>>'foo bar baz    '
```

```python
'   foo bar baz    '.rstrip()
>>>'   foo bar baz'
```

```python
"foo abc foo def fo  ljk ".replace('foo','yao')
>>>'yao abc yao def fo  ljk '
```

```python
'www.realpython.com'.strip('w.moc')
>>>'realpython'
```

```python
'www.realpython.com'.strip('w.com')
>>>'realpython'
```

```python
'www.realpython.com'.strip('w.ncom')
>>>'realpyth'
```

### **Convert to list** <a href="#convert-to-lists" id="convert-to-lists"></a>

```python
', '.join(['foo','bar','baz','qux'])
>>>'foo, bar, baz, qux'
```

```python
list('corge')
>>>['c', 'o', 'r', 'g', 'e']
```

```python
':'.join('corge')
>>>'c:o:r:g:e'
```

```python
'www.foo'.partition('.')
>>>('www', '.', 'foo')
```

```python
'foo@@bar@@baz'.partition('@@')
>>>('foo', '@@', 'bar@@baz')
```

```python
'foo@@bar@@baz'.rpartition('@@')
>>>('foo@@bar', '@@', 'baz')
```

```python
'foo.bar'.partition('@@')
>>>('foo.bar', '', '')
```

```python

'foo bar adf yao'.rsplit()
>>>['foo', 'bar', 'adf', 'yao']
```

```python
'foo.bar.adf.ert'.split('.')
>>>['foo', 'bar', 'adf', 'ert']
```

```python
'foo\nbar\nadfa\nlko'.splitlines()
>>>['foo', 'bar', 'adfa', 'lko']
```

## 总结 <a href="#zong-jie" id="zong-jie"></a>

除了我以上总结的这些，还有太多非常实用的方法，大家可以根据自己的需求去搜索

* Github仓库地址： [https://github.com/yaozeliang/pandas\_share](https://github.com/yaozeliang/pandas_share/tree/master/Pandas%E4%B9%8B%E6%97%85_04%20pandas%E8%B6%85%E5%AE%9E%E7%94%A8%E6%8A%80%E5%B7%A7)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://zeliang-yao.gitbook.io/my-note-zeliang-yao/useful/untitled-2.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
